简体   繁体   English

jQuery scrollTop跨浏览器不一致

[英]jQuery scrollTop inconsistent across browsers

In Chrome and Safari, $("body").scrollTop(1000) goes where expected. 在Chrome和Safari中, $("body").scrollTop(1000)预期。

In IE and FF, nothing happens. 在IE和FF中,没有任何反应。

In IE and FF, $(window).scrollTop(1000) works, but they go to different places. 在IE和FF中, $(window).scrollTop(1000)可以工作,但是它们会转到不同的地方。 It also works in Chrome and Safari, but they both go to a different place as well. 它也可以在Chrome和Safari中使用,但它们也可以在不同的地方使用。 They seems to be up to 300-500 pixels off. 他们似乎关闭了高达300-500像素。

Is there any consistent way to set the scrollTop property that works cross browser, and if not, why doesn't jQuery abstract this? 是否有任何一致的方法来设置跨浏览器工作的scrollTop属性,如果没有,为什么jQuery不抽象这个?

I'd like to animate it as well, which works fine in Chrome and Safari, but not in the other browsers. 我也希望为它制作动画,这在Chrome和Safari中运行良好,但在其他浏览器中则无效。

Is my only option to do browser detection? 我是浏览器检测的唯一选择吗? (bad practice) Or is there some better way? (不好的做法)或者有更好的方法吗?

$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: myTop }, myDur);

Webkit browsers (Chrome/Safari, both Mac and Win) use "body", others (FF/Opera/IE 7-9) use "html" Webkit浏览器(Chrome / Safari,Mac和Win)使用“body”,其他(FF / Opera / IE 7-9)使用“html”

Gotta love browser detection. 一定要喜欢浏览器检测。

尝试

$(document).scrollTop("...");

You need to apply scrollTop to either body or html depending on the browser, but there's no harm applying it to both. 您需要根据浏览器将scrollTop应用于bodyhtml ,但将它应用于两者都没有任何危害。 Since .scrollTop() applies to the first element in the set, but .animate() applies to all elements, you can do this: 由于.scrollTop()适用于集合中的第一个元素,但.animate()适用于所有元素,您可以这样做:

$('body, html').animate({
  scrollTop: 1000
}, 'fast');

If you want the change to apply immediately, change the speed ( 'fast' ) to 0 . 如果要立即应用更改,请将速度( 'fast' )更改为0 Alternatively, you can use the following, but I like the above syntax better: 或者,您可以使用以下内容,但我更喜欢上面的语法:

$('body, html').each(function() { $(this).scrollTop(1000); });

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

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