JavaScript获取窗口X / Y位置以进行滚动 [英] JavaScript get window X/Y position for scroll

查看:254
本文介绍了JavaScript获取窗口X / Y位置以进行滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望找到一种方法来获取当前可视窗口的位置(相对于总页面宽度/高度),这样我就可以使用它来强制从一个部分滚动到另一个部分。但是,当猜测哪个对象保留了浏览器的真实X / Y时,似乎有大量的选项。

I'm hoping to find a way to get the current viewable window's position (relative to the total page width/height) so I can use it to force a scroll from one section to another. However, there seems to be a tremendous amount of options when it comes to guessing which object holds the true X/Y for your browser.

我需要哪些这些确保IE 6 +,FF 2+和Chrome / Safari正常工作?

Which of these do I need to make sure IE 6+, FF 2+, and Chrome/Safari work?

window.innerWidth
window.innerHeight
window.pageXOffset
window.pageYOffset
document.documentElement.clientWidth
document.documentElement.clientHeight
document.documentElement.scrollLeft
document.documentElement.scrollTop
document.body.clientWidth
document.body.clientHeight
document.body.scrollLeft
document.body.scrollTop

还有其他人吗?一旦我知道窗口在哪里,我就可以设置一个事件链,它将慢慢调用 window.scrollBy(x,y); 直到达到我想要的点。

And are there any others? Once I know where the window is I can set an event chain that will slowly call window.scrollBy(x,y); until it reaches my desired point.

推荐答案

jQuery(v1.10)用于查找的方法是:

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

即:


  • 首先测试 window.pageXOffset 并使用它(如果存在)。

  • 否则,它使用 document.documentElement.scrollLeft

  • 然后减去 document.documentElement.clientLeft 如果它存在。

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

document.documentElement.clientLeft / <$ c $的减法c> Top 似乎只需要更正你已经将边框(不是填充或边距,但实际边框)应用于根元素的情况,并且可能仅在某些浏览器中。

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

这篇关于JavaScript获取窗口X / Y位置以进行滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆