Gor*_*oro 13 javascript css jquery user-interface
有没有办法可靠地告诉浏览器的视口宽度,包括滚动条,而不是浏览器窗口的其余部分)?
这里列出的所有属性都没有告诉我屏幕的宽度包括滚动条(如果有的话)
我想出了如何使用以下代码准确地使用滚动条获取视口宽度:http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript
把它放在你的 $(document).ready(function()
$(document).ready(function(){
$(window).on("resize", function(){
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
});
// Get the correct window sizes with these declarations
windowHeight = viewport().height;
windowWidth = viewport().width;
});
Run Code Online (Sandbox Code Playgroud)
它能做什么:
当您的页面"准备就绪"或调整大小时,该函数会计算正确的窗口高度和宽度(包括滚动条).
我假设您想知道包含滚动条的视口宽度,因为它自己的屏幕没有滚动条.事实上,屏幕宽度和高度将是计算机屏幕分辨率本身,所以我不确定你对滚动条的屏幕宽度是什么意思.
然而,视口,仅向用户呈现页面(和滚动条)的区域,意味着没有浏览器菜单,没有书签或其他,仅呈现的页面,是可以存在这样的滚动条的地方.
假设您需要它,您可以测量客户端浏览器视口大小,同时考虑滚动条的大小.
首先不要忘记将身体标签设置为100%宽度和高度,以确保测量准确.
body {
width: 100%;
// if you wish to also measure the height don't forget to also set it to 100% just like this one.
}
Run Code Online (Sandbox Code Playgroud)
之后您可以随意测量宽度.
样品
// First you forcibly request the scroll bars to be shown regardless if you they will be needed or not.
$('body').css('overflow', 'scroll');
// Viewport width with scroll bar.
var widthWithScrollBars = $(window).width();
// Now if you wish to know how many pixels the scroll bar actually has
// Set the overflow css property to forcibly hide the scroll bar.
$('body').css('overflow', 'hidden');
// Viewport width without scroll bar.
var widthNoScrollBars = $(window).width();
// Scroll bar size for this particular client browser
var scrollbarWidth = widthWithScrollBars - widthNoScrollBars;
// Set the overflow css property back to whatever value it had before running this code. (default is auto)
$('body').css('overflow', 'auto');
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
只要身体是100%,document.body.scrollWidth就会奏效.
演示:http://jsfiddle.net/ThinkingStiff/5j3bY/
HTML:
<div id="widths"></div>
Run Code Online (Sandbox Code Playgroud)
CSS:
body, html
{
margin: 0;
padding: 0;
width: 100%;
}
div
{
height: 1500px;
}
Run Code Online (Sandbox Code Playgroud)
脚本:
var widths = 'viewport width (body.scrollWidth): '
+ document.body.scrollWidth + '<br />'
+ 'window.innerWidth: ' + window.innerWidth + '<br />';
document.getElementById( 'widths' ).innerHTML = widths;
Run Code Online (Sandbox Code Playgroud)
我在演示中放了一个高大的div来强制滚动条.
| 归档时间: |
|
| 查看次数: |
17633 次 |
| 最近记录: |