谁能帮我一步步分析下JS的 " onmousedown事件 " 代码,指出问题所在.源代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style media="screen">
body,div,ul,li{
padding: 0;
margin: 0;
font-size: 0;
letter-spacing: -4px;
position: relative;
}
div.all{
width: 400px;
height: 12000px;
margin: 0 auto;
border: 1px solid black;
/*overflow: hidden;*/
}
div span.totop{
display: block;
color: #fff;
background-color: rgba(0, 0, 0, 0.5);
cursor: pointer;
position: fixed;
text-align: center;
width: 60px;
height: 60px;
line-height: 60px;
font-size: 20px;
letter-spacing: 0;
left: 50%;
bottom: 50px;
margin-left: -30px;
}
</style>
</head>
<body>
<div class="all">
<span class="totop">顶部</span>
</div>
<script type="text/javascript">
var spanTotop= document.querySelector("span.totop");
var itimerAnother,
iPosition;
window.onscroll= function(){
iPosition= document.documentElement.scrollTop|| document.body.scrollTop;
console.log(iPosition);
}
spanTotop.onmousedown= function(){
iPosition= document.documentElement.scrollTop|| document.body.scrollTop;
itimerAnother= setInterval(function(){
iPosition= iPosition- Math.ceil(iPosition/ 10);
document.documentElement.scrollTop= iPosition;
document.body.scrollTop= iPosition;
},10);
if(iPosition<= 0){
clearInterval(itimerAnother);
// 为什么把 clearInterval 放在外面清除不了 setInterval -------------------------
// 放在 setInterval 里面就可以 ---------------------------
}
}
</script>
</body>
</html>
先谢谢了...
从新解释一下,在第一次
mousedown
的时候,假如iPosition
大于0,此时不会执行clearInterval
,执行setInterval
,此时itimerAnother
为1
,会一直执行下去。不会停止,此时再次点击mousedown
,假如iPosition
等于0,会又一次执行setInterval
,此时itimerAnother
为2
,并且会立刻clearInterval
掉,但是itimerAnother
为1
的对象一直都没有clearInterval
掉,所以也不会停下来,要想解决这个问题,你把clearInterval(itimerAnother-1)
;加到clearInterval(itimerAnother)
前面就可以了,又试了一下,即使放到
setInterval
里面,你在iPosition
向上滚动的时候,连续触发mousedown
也会出现bug
,解决方案有两个第一个,clearInterval
放到setInterval
里面,然后点击一次后禁止再触发mousedown
,第二种方法onmosuedown
改成下面的