简体   繁体   English

用于检测浏览器窗口的scrollTop的跨浏览器方法

[英]Cross-browser method for detecting the scrollTop of the browser window

What is the best cross-browser way to detect the scrollTop of the browser window? 检测浏览器窗口的scrollTop的最佳跨浏览器方式是什么? I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight. 我不想使用任何预先构建的代码库,因为这是一个非常简单的脚本,我不需要所有这些自重。

function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers except IE before #9
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}

alert(getScrollTop())

或者只是简单:

var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

If you don't want to include a whole JavaScript library, you can often extract the bits you want from one. 如果您不想包含整个JavaScript库,则通常可以从中提取所需的位。

For example, this is essentially how jQuery implements a cross-browser scroll(Top|Left): 例如,这实际上是jQuery如何实现跨浏览器滚动(Top | Left):

function getScroll(method, element) {
  // The passed in `method` value should be 'Top' or 'Left'
  method = 'scroll' + method;
  return (element == window || element == document) ? (
    self[(method == 'scrollTop') ? 'pageYOffset' : 'pageXOffset'] ||
    (browserSupportsBoxModel && document.documentElement[method]) ||
    document.body[method]
  ) : element[method];
}
getScroll('Top', element);
getScroll('Left', element);

Note: you'll notice that the above code contains a browserSupportsBoxModel variable which is undefined. 注意:您会注意到上面的代码包含一个未定义的browserSupportsBoxModel变量。 jQuery defines this by temporarily adding a div to the page and then measuring some attributes in order to determine whether the browser correctly implements the box model. jQuery通过临时向页面添加div然后测量一些属性来定义它 ,以确定浏览器是否正确实现了盒子模型。 As you can imagine this flag checks for IE. 你可以想象这个标志会检查IE。 Specifically, it checks for IE 6 or 7 in quirks mode . 具体来说,它以怪癖模式检查IE 6或7 Since the detection is rather complex, I've left it as an exercise for you ;-), assuming you have already used browser feature detection elsewhere in your code. 由于检测相当复杂,我把它作为练习留给你;-),假设你已经在代码的其他地方使用了浏览器 功能 检测

Edit: If you haven't guessed already, I strongly suggest you use a library for these sorts of things. 编辑:如果您还没有猜到,我强烈建议您使用库来处理这些事情。 The overhead is a small price to pay for robust and future-proof code and anyone would be much more productive with a cross-browser framework to build upon. 对于强大且面向未来的代码而言,开销是一个很小的代价,任何人都可以通过跨浏览器框架来提高效率。 (As opposed to spending countless hours banging your head against IE). (而不是花费无数个小时撞击IE)。

I've been using window.scrollY || document.documentElement.scrollTop 我一直在使用window.scrollY || document.documentElement.scrollTop window.scrollY || document.documentElement.scrollTop . window.scrollY || document.documentElement.scrollTop

window.scrollY covers all browsers except IEs. window.scrollY涵盖除IE之外的所有浏览器。
document.documentElement.scrollTop covers IE. document.documentElement.scrollTop涵盖IE。

function getSize(method) {
  return document.documentElement[method] || document.body[method];
}
getSize("scrollTop");

YUI 2.8.1 code does this: YUI 2.8.1代码执行此操作:

function getDocumentScrollTop(doc) 
{
   doc = doc || document;

   //doc.body.scrollTop is IE quirkmode only
   return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
}

I think jQuery 1.4.2 code (a bit translated for humans) and supposing I understood it properly does this: 我认为jQuery 1.4.2代码(有点翻译为人类)并假设我理解它是正确的:

function getDocumentScrollTop(doc) 
{
   doc = doc || document;
   win = doc.defaultView || doc.parentWindow; //parentWindow is for IE < 9

   result = 0;
   if("pageYOffset" in win) //I'don't know why they use this, probably they tested it to be faster than doing: if(typeof win.pageYOffset !== 'undefined')
      result = win.pageYOffset;
   else
      result = (jQuery.support.boxModel && document.documentElement.scrollTop) || 
               document.body.scrollTop;

   return result;
}

Unfortunatley extracting the value of jQuery.support.boxModel is almost impossible because you would have to add a temporary child element into document and do the same tests jQuery does. Unfortunatley提取jQuery.support.boxModel的值几乎是不可能的,因为你必须在文档中添加一个临时子元素并执行jQuery所做的相同测试。

I know its been quite a while since this thread was updated, but this is a function I created that allows developers to find the root element that actually hosts has a working "scrollTop" property. 我知道自从这个线程更新以来已经有一段时间了,但这是我创建的一个函数,它允许开发人员找到实际主机具有工作“scrollTop”属性的根元素。 Tested on Chrome 42 and Firefox 37 for Mac OS X (10.9.5): 测试适用于Mac OS X的Chrome 42和Firefox 37(10.9.5):

function getScrollRoot(){
    var html = document.documentElement, body = document.body,
        cacheTop = ((typeof window.pageYOffset !== "undefined") ? window.pageYOffset : null) || body.scrollTop || html.scrollTop, // cache the window's current scroll position
        root;

    html.scrollTop = body.scrollTop = cacheTop + (cacheTop > 0) ? -1 : 1;
    // find root by checking which scrollTop has a value larger than the cache.
    root = (html.scrollTop !== cacheTop) ? html : body;

    root.scrollTop = cacheTop; // restore the window's scroll position to cached value

    return root; // return the scrolling root element
}

// USAGE: when page is ready: create a global variable that calls this function.

var scrollRoot = getScrollRoot();

scrollRoot.scrollTop = 10; // set the scroll position to 10 pixels from the top
scrollRoot.scrollTop = 0; // set the scroll position to the top of the window

I hope you find this useful! 希望这个对你有帮助! Cheers. 干杯。

This works well from IE5 to IE11. 从IE5到IE11,这很好用。 It also supports all major new browsers. 它还支持所有主要的新浏览器。

var scrollTop = (document.documentElement && document.documentElement.scrollTop) ||
                (document.body.scrollTop) || (document.scrollingElement);

I believe the best way to get scrollTop in modern browsers is to use 我相信在现代浏览器中获取scrollTop的最佳方法是使用

const scrollTop = document.scrollingElement.scrollTop

if this doesn't work you could also try 如果这不起作用你也可以尝试

const scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop, document.scrollingElement.scrollTop)

No need extra library, use this snippet: 不需要额外的库,使用此代码段:

const scrollTop = 
    (window.pageYOffset !== undefined) ? 
     window.pageYOffset :
    (document.documentElement || document.body.parentNode || document.body).scrollTop;

to save you all the trouble use a framework such as jquery or mootools that calculates all these values in one line (cross browser) in mootools its $('element').getTop(); 为了省去所有麻烦,使用jquery或mootools这样的框架,在mootools中计算所有这些值(交叉浏览器)的$('element')。getTop(); in jquery you will need a plugin named dimensions if i remember correctly although most of the time even without a framework you can actually use element.getScrollTop(); 在jquery中你需要一个名为dimension的插件,如果我没记错的话虽然大多数时候即使没有框架你也可以实际使用element.getScrollTop(); to get what you'll need the only problem is on IE7 and below this calculation is somewhat buggy as it doesn not take the position value of the element into consideration for example if you got a position: absolute css attribute for that element the calculation is performed on the parent element of that element 得到你需要的唯一的问题是IE7及以下这个计算有点错误,因为它没有考虑元素的位置值,例如,如果你有一个位置:该元素的绝对css属性,计算是在该元素的父元素上执行

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

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