Как получить размеры экрана, окна и веб-страницы в 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. Заключение
Надеюсь, теперь Вы понимаете, как получать различные размеры.
Размер экрана — это размер монитора (или дисплея), а доступный размер экрана — это размер экрана без панелей инструментов ОС.
Внешний размер окна — это размер активного окна браузера (включая поисковую строку, панель вкладок, открытые боковые панели и проч.), а внутренний размер окна — это размер области просмотра.
Наконец, размер веб-страницы — это размер контента.
jquery $(window).width() and $(window).height() return different values when viewport has not been resized
I am writing a site using jquery that repeatedly calls $(window).width() and $(window).height() to position and size elements based on the viewport size.
In troubleshooting I discovered that I am getting slightly different viewport size reports in repeated calls to the above jquery functions when the viewport is not resized.
Wondering if there is any special case anyone knows of when this happens, or if this is just the way it is. The difference in sizes reported are 20px or less, it appears. It happens in Safari 4.0.4, Firefox 3.6.2 and Chrome 5.0.342.7 beta on Mac OS X 10.6.2. I didn’t test other browsers yet because it doesn’t appear to be specific to the browser. I was also unable to figure out what the difference depends upon, if it isn’t the viewport size, could there be another factor that makes the results differ?
Any insight would be appreciated.
It is not the values of $(window).width() and $(window).height() that are changing. It’s the values of the variables I am using to store the values of the above.
It is not scrollbars that are afecting the values, no scrollbars appear when the variable values change. Here is my code to store the values in my variables (which I am doing just so they are shorter).
(all this is within $(document).ready() )
//initially declare the variables to be visible to otehr functions within .ready()
I inserted an alert statement to probe the variables above against the values they are supposed to be holding. The $(item).param() values stay consistent, but my variables change for reasons I can’t figure out.
I have looked for places where my code might be altering the value of the variables in question, as opposed to just retrieving their set values and can find none. I can post the whole shebang somewhere if that’s a possibility.
8 Tools to Measure Length, Width and Height on Your Computer Screen
If you want to know the dimensions of a physical object, you wouldn’t necessarily think of turning to your computer first to get some measurements. Of course, there are tools around that can easily tell you how many pixels on the screen it is from one point to another, but actually measuring something in inches or centimeters is a little more tricky.
Whether you want to find out if a button is placed correctly on a webpage or an object is in the correct position in your graphic work, or even if you want the dimensions of a real object but don’t have a ruler or tape measure to hand, there are utilities available to help you out.
Here are 8 free options to help you find out a variety of different measurements either in the real world or virtually on the screen.
Before You Start:
To use one of these rulers for more accurate measurements or to measure a physical object, the ruler needs to be calibrated so the inch/centimeter scaling is correct. This differs from screen to screen because of different resolutions and physical screen sizes. Some options offer an ability to calibrate against a real world object of known dimensions, but if they don’t, try the following.
You need to know the resolution of the current display (e.g. 1920×1080) and its exact visible display size in inches. (e.g. 21.5). Using a value of 22 inches when your monitor is actually 21.5 inches will produce an inaccurate measurement and needs to be as close as possible.
Once you have this information, visit the PPICalc or DPI / PPI Calculator webpage and enter the horizontal and vertical resolutions, and the diagonal screen size.
This will output a Pixels Per Inch (PPI) number which you can then enter into the ruler utility if it allows you to for better measurements. Most tools that allow this will let you enter only a whole number without decimal places, so just round up or down. Although it’s not 100%, it’s still very close.
1. JS Screen Ruler
JS Screen Ruler can display pixels, inches, pica’s, or centimeters, and the size of the ruler can simply be extended by dragging the small slider. The right click menu gives you the options to flip the ruler from horizontal to vertical, mark the exact center of the ruler, snap it to the left edge of your desktop screen, and set the pixels per inch for a more accurate measurement as mentioned above.
There is also the shareware Pro version in the zip archive which has a 15 day trial although it only offers functions like color changing and ruler rotation which you probably won’t need. JS Screen Ruler is portable and works on Windows 95 up to 7 64-bit.
2. iRuler.net
iRuler is a plain and simple webpage with a static wood effect ruler which you can measure real world objects against, or resize the browser window and drag it to where you want. Make sure to check your monitor dimensions are correct under the ruler.
If they aren’t, click the link to select from a small list, or select “even more” to enter your own and input the diagonal size of the monitor and its pixel resolution. For some reason, it asks for aspect ratio even though it really wants the vertical and horizontal screen resolution.
3. A Ruler for Windows
This measurement utility is more of a web or graphic design tool because it only measures in screen pixels and not centimeters or inches. That makes it no use for measuring real objects but it’s useful for any sort of graphics or visual work you do on your PC. As there are no centimeter or inch measurements, A Ruler for Windows doesn’t need calibrating.
The ruler itself comes with 4 different skins to choose from and a reading guide mode which turns off the numbers and markers so you can use it to read documents or books. The ruler can be flipped into vertical mode and resized or locked into position. There is also a zoom mode that can zoom into your desktop up to 4x to get more accurate measurements, keyboard shortcuts, and various measuring markers.
4. Online Ruler
We found two websites that host this online ruler. The original developer is ginifab.com and another website ursupplier.com hosts a slightly scaled back version. Besides centimeters and millimeters, the ruler can scale down to 1/32 of an inch with optional 1/8 inch markings. The original version is multi language and has a command box so you can tell it to mark certain dimensions (e.g. “show 8 3/4 inches”).
Online Ruler is very good for enabling calibration because in addition to using the standard pixels per inch method, it also has options to measure against a real world object. You can use A4 paper, a $1 bill, a €50 note, a £10 note, a CD, or a standard credit/bank card. Hold the item up to the screen and drag the ruler markings to match the object, then press Save to keep the setting for next time. Note the PPI value for future use with this or other rulers.
5. Free Online Ruler
This online ruler is pretty simple to use and has measurements for millimeters, centimeters, and inches down to 1/16 of an inch. You can also click and drag the ruler around the browser window as well as holding Ctrl and rotating it through 360°. There are checkboxes to enable/disable centimeter and inch markers and an option to flip the ruler horizontally.
Click Calibrate and you have options to calibrate the ruler against a real object. You can use a credit/bank card, a US Dollar, a sheet of A4 or Letter size paper, or use another object where its exact size is known. Drag the ruler so the markings match the object you hold up to the screen, then click the calibrate link again when that’s done.
6. MB-Ruler
There are quite a lot of advanced options available in MB-Ruler. In addition to measuring distances from one point to another using 6 different scales of measurement, it can also calculate angles with a protractor and includes its own sophisticated coordinates measuring system. A standalone portable version can be created from the options menu.
The interface is a semi transparent set square in which the center acts as the starting point for measuring and is simply grabbed and dragged around the screen to change the start point. Other notable features include a color picker, screen capture, a grid system with snapping, screen loupe function, and overlayed shapes and lines or points can be placed around the screen.
7. Screen Ruler
Besides the fact that it’s still actively in development, Screen Ruler has a number of useful functions that should cover most use cases. One of the more interesting is “measure window” that clamps itself to an open window on the desktop giving its width and height. Screen Ruler can display measurements as pixels, points, centimeters, inches, and percent (of screen width), and is available as portable and installer versions.
The ruler can be shown as vertical, horizontal, or both at once while you can also set its exact size or use a slim scale which makes the ruler thinner. Visual marker aids can be added to the ruler such as center, thirds, custom marker, or golden ratio. if you don’t like the color, it can be changed from the settings along with opacity. Calibration could be useful for high resolution monitors because you can adjust the scaling along with entering your own DPI value.
8. PickPick
PickPick is different to the other options here because it’s a free and fully featured screen capture and image editing tool. It includes a number of graphic accessory tools and one of those is a screen ruler. You probably won’t want PickPick just for the ruler but if you would like editing or screen capture functions as well, it’s a good choice. Just start the program and Pixel Ruler is listed on the right.
You can choose from a vertical or horizontal layout, measure with pixels, inches, or centimeters, choose from four colored skins, and have transparency. The ruler can be finely moved with the arrow keyboard keys. For calibration, you can select from a choice of four DPI (or PPI) settings or enter your own. There is no decimal place PPI value but rounding to the nearest whole number should be close enough.
Length vs Width
There is currently some confusion going on when distinguishing length from width. The problem is that the descriptions of the two are somewhat different depending on where you learned it. If it’s within the confines of your classroom, most students are taught in mathematics that a rectangle parallelogram (with parallel sides) will have its longest side as the length while the shorter side is the width. This is regardless of whether the longer side is the vertical side or the horizontal side. However, many have observed that the length is usually the vertical, and the width is the one in line with the horizontal plane.
The confusion continues because in some other aspects the length is not always the longest measurement of an object. For example, some wires are actually thicker (width) as opposed to cutting their shorter lengths. FET transistors also have channel widths having greater measures than their channel length. In the layman’s understanding, though, length is simply describing how long something is while width is telling someone how wide an object is.
Width is otherwise known as the breadth. It is the distance from one side to the other side which measures across a particular shape or object whose lengths are forming right angles with the sides as in the case of a rectangle.
Length and width are two fundamental one-dimensional units compared to the measurement of the rectangle’s area which is a product of two units, the length and width. There are many units of length used today. The most basic of which is the meter in the SI units of measurement. Other units for length are: foot, yard, mile, and inch for the Imperial or English units of measurement. There are also some non-SI length units like: micron, Norwegian mil, angstrom, and Fermi.
Length can also refer to an extent of time like asking how long a certain activity will take. Some also use length in the same context as distance like when one says, “Hold it at arm’s length!”
1.Length is describing how long something is while width is describing how wide an object is.
2.In geometry, length pertains to the longest side of the rectangle while width is the shorter side.
3.Length can also refer to an extent of time or a measure of distance.
4.The most common unit for measuring length is the meter.