问题
I am having trouble getting the scrollTop() method to work in both Firefox and Chrome. I used $('body, html').scrollTop(); however, it doesn't work in Chrome. Only $('body').scrollTop(); works in Chrome. Any thoughts would be greatly appreciated. Below is my code.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style type="text/css">
body {
height: 2000px;
}
#light {
display: block;
position: fixed;
top: 50%;
left: 50%;
margin-left: -400px;
margin-top: -200px;
width: 800px;
height: 400px;
background-color: blue;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="light">
</div>
<!-- Used the google jQuery link for ease of use in this example -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(window).scroll(function () {
var offset = $('body, html').scrollTop();
var view = $(window).height();
var total = $(document).height();
var percent = 1-(offset / (total - view));
var widthFactor = 800*percent;
var marginFactor = -(400*percent)
if(percent > 0.33){
$("#light").css({ "width" : widthFactor,
"margin-left" : marginFactor});
};
});
});
</script>
</body>
</html>
回答1:
Use the document object instead
$(document).scrollTop();
回答2:
I had this same issue. Best solution for me was to do it on window:
var offset = $(window).scrollTop();
In order for this to work though, your body and html elements can't have a height set to 100%. use min-height instead
EDIT: the HTML element can use height: 100%, however if you need the body to stretch to full height you have to use min-height: 100% instead. Otherwise the scrollTop always returns "0"
回答3:
Try this, this is scroll on top with animation which is seen more effective
$("html, body").animate({ scrollTop: 0 }, 2000);
Demo Here
回答4:
You use multiple selector and it will return an array of DOM elements. Calling getter function of this array seems undefined in Chrome (setter functions should work)?
Anyway you can use $('body').scrollTop() || $('html').scrollTop() in you case.
Or just $(document) as mentioned in Justin's answer.
回答5:
Used this solution:
window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)
Supplied in this answer in another thread: https://stackoverflow.com/a/33462363
You don't need to involve jQuery and it works fine for me.
回答6:
Remove height style from the body,html tags. Add an id to the main div under body e.g. #content then use following script. As previously quoted run $(document).scrollTop(); in the browser console and make sure it returns a value not 0.
$('body, html').animate({
scrollTop: $('#content ').offset().top
}, 1000);
回答7:
try this simple javascript code for scroll element using id
document.getElementById("id").scrollTop=0;
来源:https://stackoverflow.com/questions/18778020/cant-get-scrolltop-to-work-in-both-chrome-firefox