简体   繁体   English

检测窗口宽度并补偿滚动条 - Javascript

[英]detect window width and compensate for scrollbars - Javascript

How do I detect the width of a user's window with Javascript and account for their scrollbar? 如何使用Javascript和滚动条帐户检测用户窗口的宽度? (I need the width of the screen INSIDE of the scrollbar). (我需要滚动条内屏幕的宽度)。 Here's what I have...it seems to work in multiple browsers...except that it doesn't account for the scrollbars.. 这是我的...它似乎在多个浏览器中工作...除了它不考虑滚动条..

    function browserWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

any ideas? 有任何想法吗? i need it to work in all browsers;) 我需要它在所有浏览器中工作;)

A (markedly nasty) workaround if you're only interested in the width is to create a 1px x 100% div and use its offsetWidth. 如果您只对宽度感兴趣,那么(明显令人讨厌的)解决方法是创建1px x 100%div并使用其offsetWidth。 Works on IE>=7, FF, Chrome, Safari and Opera (I've not tried IE6, as we're working to a you're-lucky-it-works-at-all-so-don't-complain-about-rendering-oddities policy thereabouts these days). 适用于IE> = 7,FF,Chrome,Safari和Opera(我没有尝试过IE6,因为我们正在为一个你很幸运的人工作 - 所有 - 所以不要抱怨 - 这些天 - 关于渲染 - 古怪的政策。 I hang the div off document.body with attributes { position: 'absolute', top: '-1px', left: 0, width: '100%', height: '1px' } , creating it the first time it's needed. 我把div挂起了document.body,带有属性{ position: 'absolute', top: '-1px', left: 0, width: '100%', height: '1px' } ,在第一次需要时创建它。

Works if you can stomach it. 如果你可以忍受它的工作。

You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org . 您将在quirksmode.org上找到此页面上哪些浏览器支持哪些属性的大摘要。

Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight. 你最好的选择可能是在页面中获取一个元素(使用document.body支持,或者document.getElementById或其他),遍历其offsetParent链以找到最顶层的元素,然后检查该元素的clientWidth和clientHeight。

This is a more efficient version of an idea posted here by Tim Salai ( even though you are just beginning, it was brilliant to place an element in the bottom right corner like that ). 这是Tim Salai在这里发布的一个更有效的想法版本(即使你刚刚开始,在这样的右下角放置一个元素也很棒)。

var getDimensions = document.createElement("div");
getDimensions.setAttribute("style", 
            "visibility:hidden;position:fixed;bottom:0px;right:0px;");
document.getElementsByTagName("body")[0].appendChild(getDimensions);
var viewportWidth = getDimensions.offsetLeft;
var viewportHeight = getDimensions.offsetTop;

And here is a modular version 这是一个模块化版本

var PageDimensions = function(){
 var Width;
 var Height;     

 function pagedimensionsCtor (){
   var getDimensions = document.createElement("div");
   getDimensions.setAttribute("style" , 
         "visibility:hidden;position:fixed;bottom:0px;right:0px;");
   document.getElementsByTagName("body")[0].appendChild(getDimensions);
   Width = getDimensions.offsetLeft;
   Height = getDimensions.offsetTop;
   getDimensions.parentNode.removeChild(getDimensions);
 }
 pagedimensionsCtor();

 function Reset(){
  pagedimensionsCtor();
 }     

 function GetPageHeight(){
  return Height;
 }

 function GetPageWidth(){
  return Width;
 }

 return{
  Reset: Reset,
  GetPageHeight: GetPageHeight,
  GetPageWidth: GetPageWidth
 };
}

Use the modular version: 使用模块化版本:

var page = new PageDimensions();
console.log("viewportWidth: " + page.GetPageWidth() + " viewportHeight: " + page.GetPageHeight());

Bonus feature: 奖金功能:

page.Reset();//just in case you think your dimensions have changed

Just add that before the window.innerWidth() check: 只需在window.innerWidth()之前添加:

if (typeof(document.body.clientWidth) == 'number') {
    // newest gen browsers
    width = document.body.clientWidth;
    height = document.body.clientHeight;
}

This is what I did - only half a year into learning JavaScript, so this may be a bad fix. 这就是我所做的 - 只用了半年时间学习JavaScript,所以这可能是一个糟糕的修复。 First, I created a transparent square image (10px x 10px) , but you could also create a non-transparent image and add this to your JavaScript as 首先,我创建了一个透明的方形图像(10px x 10px) ,但您也可以创建一个不透明的图像并将其添加到您的JavaScript中
document.getElementById('getDimensions').style.visibility = "hidden";

HTML: HTML:

<img id="getDimensions" src="images/aSmallBox.png" alt="A small transparent image  
meant to determine the dimensions of the viewport" width="10px" height="10px"/>

JavaScript: JavaScript的:

//Inside function called by window.onload event handler (could go in CSS file, but   
//better to keep it with other related code in JS file)
document.getElementById('getDimensions').style.position = "fixed";
document.getElementById('getDimensions').style.bottom = "0px";
document.getElementById('getDimensions').style.right = "0px";   

//Everything below inside function called by window.onresize event handler
var baseWidthCalculation = document.getElementById('getDimensions').offsetLeft;
var baseHeightCalculation = document.getElementById('getDimensions').offsetTop;
  //Account for the dimensions of the square img element (10x10)
var viewportWidth = baseWidthCalculation + 10;
var viewportHeight = baseHeightCalculation + 10;

I would compare the "innerWidth" to the width of the body. 我会将“innerWidth”与身体的宽度进行比较。 If the body width > innerwidth, then scrollbars are present. 如果body width> innerwidth,则存在滚动条。

if (browserWidth() < document.body.offsetWidth) {
  doSomething();
}

Another solution you can try is changing some CSS so scrolling happens within your page, instead of the browser window doing it. 您可以尝试的另一个解决方案是更改一些CSS,以便在页面中进行滚动,而不是在浏览器窗口中进行滚动。 In the style for body, add overflow:auto. 在body的样式中,添加overflow:auto。 Now the body element includes the scrollbar, so when you get the window width you're measuring the width outside the scrolling container instead of inside it. 现在body元素包含滚动条,因此当您获得窗口宽度时,您将测量滚动容器外部的宽度而不是内部。

This does feel like a potential source of quirkiness, and possibly an accessibility issue, so if you're going for widespread use you might want to test it quite carefully. 这确实是一种潜在的怪癖来源,也可能是一个可访问性问题,所以如果你想广泛使用,你可能需要仔细测试它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM