鼠标滚动得快的时候就出现问题,怎么解决啊?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
body{
height: 2500px;
}
#Div{
background-color: red;
width: 100px;
height: 100px;
position: absolute;
right: 0;
}
#text{
width:400px;
height: 30px;
position: fixed;
}
</style>
<script type="text/javascript">
window.onscroll = function(){
var div=document.getElementById('Div');
var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
var target=parseInt(scrollTop+(document.documentElement.clientHeight-div.offsetHeight)/2);
startMove(target);
}
function startMove(target){
var timer=null;
var div=document.getElementById('Div');
clearInterval(timer);
timer=setInterval(function(){
var iSpeed=(target-div.offsetTop)/8;
iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
var text = document.getElementById('text');
text.value="目标为: "+target+" offsetTop: "+div.offsetTop+ " iSpeed:"+iSpeed;
if(div.offsetTop==target)
{
clearInterval(timer);
}
else{
div.style.top=div.offsetTop+iSpeed+'px';
}
},30);
}
</script>
</head>
<body>
<div id="Div"></div>
<input type="text" id="text"/>
</body>
</html>
定时器那里调用的有问题。
在window.onscroll的时候触发了多个定时器。
你可以多次上下滚动。会发现上下抖动的幅度变的更大。
还有。建议把定时器对象返回给startMove(target)方法。
在window.onscroll = function()调用后清除定时器
window.onscroll = function(){
var div=document.getElementById('Div');
var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
var target=parseInt(scrollTop+(document.documentElement.clientHeight-div.offsetHeight)/2);
var timer = startMove(target);
clearInterval(timer); //在这里加上清除定时器
}
你写固定效果使用css不就可以了吗?你看下这个是否符合你的要求?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
<style type="text/css">
body{margin:0; padding:0; height:3000px;}
div.div1{margin-top:100px; padding:0; width:100px; height:100px; border:1px solid #cccccc; background-color:black; position:fixed;}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<!-- div1是固定的一块 -->
<div class="div1">
</div>
<div class="test1" style="height:1000px; background-color:#cce8ef;">
</div>
<div class="test2" style="height:1000px; background-color:#bcbcbc;">
</div>
<div class="test3" style="height:1000px; background-color:blue;">
</div>
</body>
</html>