- .width()
- version added: 1.0 .width()
- version added: 1.0 .width( value )
- version added: 1.4.1 .width( function(index, width) )
- Примеры:
- Как получить размеры экрана, окна и веб-страницы в JavaScript?
- 1. Экран
- 2. Окно
- 3. Размер веб-страницы
- 4. Заключение
- Get the height and width of the browser viewport without scrollbars using jquery?
- 10 Answers 10
- Description
- Sample
- More Information
- Detect a window width change but not a height change
- 5 Answers 5
- Do something if screen width is less than 960 px
- 10 Answers 10
- Not the answer you’re looking for? Browse other questions tagged javascript jquery or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
.width()
Возвращает, устанавливает ширину элемента.
version added: 1.0 .width()
Возвращает: Целое число
Получает ширину элемента
version added: 1.0 .width( value )
value
Тип: Строка или Число
Возвращает: jQuery
Целое число, представляющее количество пикселей, или число с единицей измерения в виде строки.
version added: 1.4.1 .width( function(index, width) )
function(index, width)
Тип: Функция
Возвращает: jQuery
Функция, возвращающая ширину, чтобы установить новую. Получает индекс положения элемента в наборе и значение старой ширины. Функция ссылается к текущему элементу.
Разницу между .css(‘width’) и .width() в то, что данный метод возвращает исключительно числовое значение (к примеру, 400, а не 400px). Метод .width() рекомендуется использовать, когда полученное значение необходимо задействовать в математических вычислений.
Данный метод можно использовать для получения ширины документа и окна.
Заметьте, что метод .width() всегда возвращает ширину контента, не учитывая от значения свойства CSS box-sizing. Начиная с jQuery 1.8, вам необходимо получить значение свойства box-sizing, затем отнять размер рамки и отступов. Всё это в том случае, если к элементу применяется свойство box-sizing: border-box. Чтобы избежать этих вычислений, используйте .css(«width»).
Передать в метод .width(value), можно как строку, так и число. Если передано только число, то jQuery автоматом прибавляет “px”. Если строка, то она должна выглядеть так: 100px, 50%, или auto. Просим заметить, что в современных бразуерах в ширину не входят значения отступов и рамки.
Примеры:
Пример: Показать различия значений ширины элементов. Поскольку элементы находятся в iframe, то настоящие размеры могут быть чуть другими.
Пример: Задать при клике по элементам div различную ширину.
Как получить размеры экрана, окна и веб-страницы в JavaScript?
Доброго времени суток, друзья!
Представляю Вашему вниманию перевод небольшой заметки «How to Get the Screen, Window, and Web Page Sizes in JavaScript» автора Dmitri Pavlutin.
Для определения ориентации окна браузера (ландшафтной или портретной) можно сравнить его ширину и высоту.
Однако во всевозможных доступных размерах легко запутаться: существуют размеры экрана, окна, веб-страницы и т.д.
Что означают эти размеры и, главное, как их получить? Именно об этом я и собираюсь рассказать.
1. Экран
1.1. Размер экрана
Размер экрана — это ширина и высота всего экрана: монитора или мобильного дисплея.
Получить информацию о размере экрана можно с помощью свойства screen объекта window :
1.2. Доступный размер экрана
Доступный размер экрана — это ширина и высота активного экрана без панели инструментов операционной системы.
Для получения доступного размера экрана снова обращаемся к window.screen :
2. Окно
2.1. Размер внешнего окна (или внешний размер окна)
Размер внешнего окна — это ширина и высота текущего окна браузера, включая адресную строку, панель вкладок и другие панели браузера.
Получить информацию о размере внешнего окна можно с помощью свойств outerWidth и outerHeight объекта window :
2.2. Внутренний размер окна (или размер внутреннего окна)
Внутренний размер окна — это ширина и высота области просмотра (вьюпорта).
Объект window предоставляет свойства innerWidth и innerHeight :
Если мы хотим получить внутренний размер окна без полос прокрутки, то делаем следующее:
3. Размер веб-страницы
Размер веб-страницы — это ширина и высота отображаемого содержимого (отрендеренного контента).
Для получения размера веб-страницы используйте следующее (включает в себя внутренние отступы страницы, но не включает границы, внешние отступы и полосы прокрутки):
Если pageHeight больше, чем внутренняя высота окна, значит, присутствует вертикальная полоса прокрутки.
4. Заключение
Надеюсь, теперь Вы понимаете, как получать различные размеры.
Размер экрана — это размер монитора (или дисплея), а доступный размер экрана — это размер экрана без панелей инструментов ОС.
Внешний размер окна — это размер активного окна браузера (включая поисковую строку, панель вкладок, открытые боковые панели и проч.), а внутренний размер окна — это размер области просмотра.
Наконец, размер веб-страницы — это размер контента.
Get the height and width of the browser viewport without scrollbars using jquery?
How do I get the height and width of the browser viewport without scrollbars using jQuery?
Here is what I have tried so far:
This solution does not take into account the browser scrollbars.
10 Answers 10
More info
Using jQuery is not essential for getting those values, however. Use
to get sizes excluding scrollbars, or
to get the whole viewport, including scrollbars.
Don’t use jQuery, just use javascript for correct result:
This includes scrollbar width/height:
This excludes scrollbar width/height:
Here is a generic JS which should work in most browsers (FF, Cr, IE6+):
You’re using the wrong method calls. A viewport is the «window» that’s open on the document: how much of it you can see and where.
Using $(window).height() will not give you the viewport size it will give you the size of the entire window, which is usually the size of the entire document though the document could be even larger.
To get the size of the actual viewport use window.innerHeight and window.innerWidth .
Do not use the jQuery methods, e.g. $(window).innerHeight() , as these give the wrong numbers. They give you the window’s height, not innerHeight .
Description
The following will give you the size of the browsers viewport.
Sample
More Information
As Kyle suggested, you can measure the client browser viewport size without taking into account the size of the scroll bars this way.
Sample (Viewport dimensions WITHOUT scroll bars)
Alternatively if you wish to find the dimensions of the client viewport while taking into account the size of the scroll bars, then this sample bellow best suits you.
First don’t forget to set you body tag to be 100% width and height just to make sure the measurement is accurate.
Sample (Viewport dimensions WITH scroll bars)
The script $(window).height() does work well (showing the viewport’s height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:
for transitional html4:
Probably the default doctype assumed by some browsers is such, that $(window).height() takes the document’s height and not the browser’s height. With the doctype specification, it’s satisfactorily solved, and I’m pretty sure you peps will avoid the «changing scroll-overflow to hidden and then back», which is, I’m sorry, a bit dirty trick, specially if you don’t document it on the code for future programmer’s usage.
Moreover, if you are doing a script, you can invent tests to help programmers in your libraries, let me invent a couple:
Detect a window width change but not a height change
I’m using the .resize() function to detect window re-size events, but this detects both height and width changes.
Is there any way to detect just a width change and not a height change?
5 Answers 5
you can detect both events and just execute code when it’s a width change:
And you might want to check event debouncing.
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in «execute this function only if 100 milliseconds have passed without it being called.
Read more:
Even though there are already a couple of answers with working solutions, this kind of task is performance critical (window resize event is triggered many times while a user is resizing the window) so I strongly suggest you to take care of the performance. Please, have a look at the optimized code below:
Plus, you might be interested in checking the Debounce / Throttle patterns — they improve performance enormously in cases like this.
Keeps your own code more readable:
The link provided by @nachtigall is broken, so I found this other with the same library, which helped me to solve my issue: resize-dimension.js
Example of solution is as follow: Import library:
The function ForResize() gets fired when the browser is resized, though in this case, IE handles it better than the other browsers, however, in my case, it worked fine for mobile devices, which where firing the events when scrolling the page, which depending on the mobile browser, it can hide the address bar, which affects the browser’s size. Implementing that library helped!
I used the counter/timer provided here and modified it to my needs. The following are the critical scripts that I had to create:
Do something if screen width is less than 960 px
How can I make jQuery do something if my screen width is less than 960 pixels? The code below always fires the 2nd alert, regardless of my window size:
10 Answers 10
Use jQuery to get the width of the window.
You might want to combine it with a resize event:
I tried http://api.jquery.com/off/ with no success so I went with the eventFired flag.
I recommend not to use jQuery for such thing and proceed with window.innerWidth :
You can also use a media query with javascript.
I would suggest (jQuery needed) :
Then you can get easily window’s width with the var : windowWidth and Height with : windowHeight
I know i’m late to answer this, but i hope it is of some help to anybody who have similar problem. It also works when page refreshes for any reason.
nope, none of this will work. What you need is this.
Not the answer you’re looking for? Browse other questions tagged javascript jquery or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.