我无法让scrollTop()方法在Firefox和Chrome中都能正常工作。我使用$('body, html').scrollTop();
但是,它在Chrome中不起作用。只有$('body').scrollTop();
适用于Chrome。任何想法将不胜感激。以下是我的代码。
<!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>
答案 0 :(得分:31)
使用文档对象
$(document).scrollTop();
答案 1 :(得分:11)
我有同样的问题。对我来说最好的解决方案是在window
:
var offset = $(window).scrollTop();
为了使其正常工作,您的正文和html元素无法将height
设置为100%
。使用min-height
代替
编辑:HTML
元素可以使用height: 100%
,但是如果您需要body
拉伸到最大高度,则必须使用min-height: 100%
。否则scrollTop
总是返回“0”
答案 2 :(得分:5)
答案 3 :(得分:2)
您使用多个选择器,它将返回一个DOM元素数组。调用此数组的getter函数似乎在Chrome中未定义(setter函数应该可以工作)?
无论如何,你可以使用$('body').scrollTop() || $('html').scrollTop()
。
或者只是贾斯汀回答中提到的$(文件)。
答案 4 :(得分:1)
使用此解决方案:
window.scrollY || window.pageYOffset || document.body.scrollTop + (document.documentElement && document.documentElement.scrollTop || 0)
在另一个帖子的答案中提供: https://stackoverflow.com/a/33462363
你不需要涉及jQuery,它对我来说很好。
答案 5 :(得分:0)
从body,html标签中删除高度样式。将id添加到body下的主div中,例如#content然后使用以下脚本。如前所述,在浏览器控制台中引用了$(document).scrollTop();
并确保它返回的值不是0。
$('body, html').animate({
scrollTop: $('#content ').offset().top
}, 1000);
答案 6 :(得分:0)
使用id
为滚动元素尝试这个简单的javascript代码document.getElementById("id").scrollTop=0;