简体   繁体   English

Javascript window.scrollTo不同浏览器上的行为

[英]Javascript window.scrollTo Behavior On Different Browsers

I'm facing an issue with the scrollTo function when the body has an dir=rtl attribute. 当正文具有dir = rtl属性时,scrollTo函数遇到问题。 here is a jsfiddle for my case. 这是我的情况的jsfiddle

HTML: HTML:

  window.scrollTo(-200, 0); 
 <html> <head> </head> <body dir="rtl"> <div width="100%" style="width: 3000px; height:200px; overflow: hidden"> <div style="width: 1000px; height: 100px; border: 2px solid black; display: inline-block"></div> <div style="width: 1000px; height: 100px; border: 2px solid red; display: inline-block"></div> </div> <script type="text/javascript"> window.scrollTo(-200, 0); </script> </body> </html> 

So if I pass a positive value for the xpos parameter, it works on IE (sort of) naturally, it scrolls from the right side of the screen for an amount of 200px. 因此,如果我为xpos参数传递一个正值,那么它自然就可以在IE(某种程度上)上运行,它会从屏幕的右侧滚动200px。 but on chrome and firefox it doesn't work, I have to pass a negative value for the scrolling to work as expected. 但是在chrome和firefox上它不起作用,我必须传递一个负值才能使滚动按预期工作。

My question, is how I can handle this case in my code, should I do browser sniffing? 我的问题是,如何在我的代码中处理这种情况,我应该进行浏览器嗅探吗? or is there a better way? 或者,还有更好的方法? some feature I can test if its supported? 我可以测试某些功能是否受支持?

This snippet worked for me on IE and Chrome 此代码段适用于IE和Chrome浏览器

http://jsfiddle.net/05w4tr0g/4/ http://jsfiddle.net/05w4tr0g/4/

var m = -1;
var pos = window.pageXOffset;
window.scrollTo(0,0);
window.scrollTo(1, 0);
if (-1 == window.pageXOffset) m = 1;
window.scrollTo(pos, 0);
window.scrollTo(m*200, 0);

Hope that helps. 希望能有所帮助。 The idea is that that the pageXOffset is with IE and Chrome always negative if there was scrolling. 这个想法是,pageXOffset与IE一起使用,而Chrome在滚动时始终为负数。 The snippet will cause a little flicker because of the test scroll to x=0 and x=-1. 由于测试滚动到x = 0和x = -1,该代码段将引起少许闪烁。 You could store the m value on a page load and reuse it in a wrapper function for scrollTo (or scrollBy for that matter). 您可以将m值存储在页面加载中,并在scrollTo(或为此的scrollBy)的包装函数中重新使用它。 You could also overload the two methods and keep it all in the window context. 您还可以重载这两种方法,并将其全部保留在窗口上下文中。

as othree explains in his jQuery rtl scroll type plugin there are 3 main implementations for horizontal scrolling when dir is set to rtl : WebKit, Firefox/Opera and IE 正如其他人在他的jQuery rtl滚动类型插件中解释的那样 ,当dir设置为rtl时,水平滚动的主要实现有3种:WebKit,Firefox / Opera和IE

the difference between these implementations is as follows: 这些实现之间的区别如下: 滚动类型

because you can't use jQuery I've modified othree code in this plunker and it works fine in chrome, firefox and IE11 因为您无法使用jQuery,所以我已经在此插件中修改了其他代码,并且在chrome,firefox和IE11中都可以正常工作

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

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