以下JS代码有效,但offset()。top和scrollTop()的值分别保持为0。
$("body, html").scroll(function() {
// event triggers on scrolling
var foo = $("body, html").offset().top;
var bar = $("body, html").scrollTop();
console.log(foo); // ==> 0 all the time
console.log(bar); // ==> 0 all the time
});
我有一种不好的感觉,这与CSS溢出有某种联系,但我无法弄明白。
这里是runnable片段:
$("body, html").scroll(function() {
var bar = $(this).scrollTop(); console.log(bar);
});
html {
overflow: auto;
height: 100%;
}
body {
overflow: auto;
height: 100%;
overflow-x: hidden;
}
div {
background: #FF9900;
}
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<div style="height: 1000px;">Hi there.</div>
</body>
</html>
答案 0 :(得分:1)
是的,这与CSS溢出有关。您不应该在不需要时明确指定溢出,例如在您设置的body和html标记上,div的长度会导致正文在这种情况下滚动。设置这些溢出:自动属性会导致与两个滚动条冲突,并且可以给你一些不稳定的结果。
我已经设置了这个类似于你的基本示例,仅用于测试并且它有效。 scrollTop应该改变。 offsetTop保持为0,因为整个身体都是静止的,你只是向下滚动。
<html>
<style>
body {
overflow-x: hidden;
}
div {
background: #FF9900;
}
</style>
<head>
</head>
<body id='body'>
<div id="test" style="height: 1000px;">Hi there. Click me.</div>
<script>
document.getElementById('body').addEventListener('click', function() {
var scrollthing = document.getElementById('body').scrollTop;
var scrollthing2 = document.getElementById('body').offsetTop;
console.log('SCROLLTOP IS' + scrollthing);
console.log('OFFSETTOP IS' + scrollthing2);
});
</script>
</body>
</html>
答案 1 :(得分:0)
使用窗口。正文和HTML始终位于顶部。
$(window).scrollTop()