scrollTop() returns 0 in Firefox, but not in Chrome

北城以北 提交于 2019-11-27 15:46:21

问题


Not sure if there's another question regarding this, if so I apologize and please don't release the hounds.

Using the html5 doctype and doing a quick console.log off my scroll listener that tells me the value of scrollTop() value. I'm basically doing this so when I scroll past a point, I change the opacity of an element. I'm doing this using an MVS solution and I don't have the ability to push this to an external site so you can look. Here's a quick snippet:

var opacity = 1;
var scrollTop = $('body').scrollTop();
if (scrollTop > 200) {
   opacity = 0.1;
}
$('#element).css('opacity', opacity);

If I scroll in Chrome, I get a console.log(scrollTop); displaying what I want (ie; 100 for each scroll I do) and my opacity disappears after I hit 200 scrollTop. If I scroll in FF and IE7+ the var returns "0" each scroll. If I change $('body').scrollTop() to $('document').scrollTop(); then I get a "null" return on scroll.

Any ideas? Thanks!


回答1:


Try to use var scrollTop = $(document).scrollTop();




回答2:


$(window).scrollTop() works as expected in both Firefox and Chrome.

For verification run the following jsfiddle in both chrome and firefox: http://jsfiddle.net/RBBw5/6/




回答3:


After some frustration with IE9 in quirks mode, I've found the that $('body').scrollTop() works reliably in IE9, Chrome 32 and Firefox 26.




回答4:


Use var scrollTop = $('html').scrollTop(); works for FireFox

You'll need to sniff the browser out though (I know, feature detect, not sniff, but you can't detect this), because it won't work in Chrome, try here :

Easiest/Lightest Replacement For Browser Detection jQuery 1.9?



来源:https://stackoverflow.com/questions/12941150/scrolltop-returns-0-in-firefox-but-not-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!