Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante. Vestibulum id metus ac nisl bibendum scelerisque non non purus. Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit amet elementum vestibulum. Vivamus fermentum in arcu in aliquam. Quisque aliquam porta odio in fringilla non purus nisld Dapibus nec turpis vel, semper malesuada ant.
Output
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.
In the above jQuery height() method example, First of all When you click on button that get selected html elements height and after that we have set height of the selected html elements and showing the current height of the box body.
Recommended jQuery Tutorial
How to Get & Set Data Attribute Value From Elements jQuery
jQuery Remove Attribute and Disabled Attribute From Element
jQuery | Event MouseUp By Example
Event jQuery Mouseleave By Example
jQuery Event Mouseenter Example
Event jQuery MouseOver & MouseOut By Example
keyup jquery event example
Jquery Click Event Method with E.g.
Event jQuery. Blur By Example
jQuery form submit event with example
keydown function jQuery
List of jQuery Events Handling Methods with examples
Jquery Selector by .class | name | #id | Elements
How to Get the Current Page URL in jQuery
jQuery Ajax Get() Method Example
get radio button checked value jquery by id, name, class
jQuery Set & Get innerWidth & innerHeight Of Html Elements
jQuery Get Data Text, Id, Attribute Value By Example
Set data attribute value jquery
select multiple class in jquery
How to Remove Attribute Of Html Elements In jQuery
How to Checked Unchecked Checkbox Using jQuery
jQuery removeClass & addClass On Button Click By E.g.
To Remove whitespace From String using jQuery
jQuery Ajax Post Method Example
jQuery Ajax Get Method Example
To Load/Render html Page in div Using jQuery Ajax $.load
jQuery Sibling Methods – To Find Siblings Elements
jQuery Find Siblings Elements with Class, id
Author Admin
My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.
Источник
.width()
Get the current computed width for the first element in the set of matched elements or set the width of every matched element.
Contents:
.width() Returns: Number
Description: Get the current computed width for the first element in the set of matched elements.
version added: 1.0 .width()
The difference between .css( "width" ) and .width() is that the latter returns a unit-less pixel value (for example, 400 ) while the former returns a value with units intact (for example, 400px ). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.
This method is also able to find the width of the window and document.
// Returns width of browser viewport
// Returns width of HTML document
Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box . To avoid this penalty, use .css( "width" ) rather than .width() .
Note: Although style and script tags will report a value for .width() or height() when absolutely positioned and given display:block , it is strongly discouraged to call those methods on these tags. In addition to being a bad practice, the results may also prove unreliable.
Additional Notes: The number returned by dimensions-related APIs, including .width() , may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition. The value reported by .width() is not guaranteed to be accurate when the element or its parent is hidden. To get an accurate value, ensure the element is visible before using .width() . jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery. Example: Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
script src ="https://code.jquery.com/jquery-3.7.0.js" > script>
button id ="getp" >Get Paragraph Width button>
button id ="getd" >Get Document Width button>
button id ="getw" >Get Window Width button>
Sample paragraph to test width
function showWidth ( ele, w )
$( "div" ).text( "The width for the " + ele + " is " + w + "px." );
$( "#getp" ).on( "click" , function ( )
showWidth( "paragraph" , $( "p" ).width() );
$( "#getd" ).on( "click" , function ( )
showWidth( "document" , $( document ).width() );
$("#getw" ).on( "click" , function ( )
showWidth( "window" , $( window ).width() );
Demo: .width( value ) Returns: jQuery Description: Set the CSS width of each element in the set of matched elements.
version added: 1.0 .width( value ) An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).
version added: 1.4.1 .width( function ) A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.
When calling .width("value") , the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit. If a string is provided, however, any valid CSS measurement may be used for the width (such as 100px , 50% , or auto ). Note that in modern browsers, the CSS width property does not include padding, border, or margin, unless the box-sizing CSS property is used.
If no explicit unit is specified (like "em" or "%") then "px" is assumed.
Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property.
Example: Change the width of each div the first time it is clicked (and change its color).
Источник
.width()
Разницу между .css('width') и .width() в то, что данный метод возвращает исключительно числовое значение (к примеру, 400, а не 400px). Метод .width() рекомендуется использовать, когда полученное значение необходимо задействовать в математических вычислений.
Данный метод можно использовать для получения ширины документа и окна.
$(window).width(); $(document).width(); Заметьте, что метод .width() всегда возвращает ширину контента, не учитывая от значения свойства CSS box-sizing. Начиная с jQuery 1.8, вам необходимо получить значение свойства box-sizing, затем отнять размер рамки и отступов. Всё это в том случае, если к элементу применяется свойство box-sizing: border-box. Чтобы избежать этих вычислений, используйте .css("width").
Передать в метод .width(value), можно как строку, так и число. Если передано только число, то jQuery автоматом прибавляет “px”. Если строка, то она должна выглядеть так: 100px, 50%, или auto. Просим заметить, что в современных бразуерах в ширину не входят значения отступов и рамки.
Примеры: Пример : Показать различия значений ширины элементов. Поскольку элементы находятся в iframe, то настоящие размеры могут быть чуть другими.
body < background:yellow; >button < font-size:12px; margin:2px; >p < width:150px; border:1px red solid; >div Get Paragraph Width Get Document Width Get Window Width Sample paragraph to test width
Пример : Задать при клике по элементам div различную ширину.
div < width: 70px; height: 50px; float:left; margin: 5px; background: red; cursor: pointer; >.mod d
d
d
d
d
Источник