為啥鼠標上下來回滾動時候,li消失,或者無限制的增加,是瀏覽器運行比較卡,還是代碼問我。
<!DOCTYPE html>
<html>
??? <head>
??????? <meta charset="UTF-8">
??????? <title></title>
??? </head>
??? <style type="text/css">
??????? *{margin: 0;padding: 0;}
??????? ul{list-style: none;}
??????? li{width: 200px;height: 100px;background: #8B4513;margin-top: 10px;}
?????? ?
??? </style>
??? <script type="text/javascript">
??? window.onload=function(){
??????? var lia=document.getElementsByTagName("li");
??????? for(var i=0;i<lia.length;i++){
??????????? lia[i].timer=null;
??????????? lia[i].onmouseover=function(){
?????????? ??? ?startMove(this,400);
??????????? }
??????????? lia[i].onmouseout=function(){
??????????? startMove(this,200);
??????? }
??? }
?????? }
??????? function startMove(obj,target){
??????????? clearInterval(obj.timer);
??????????? var speed=(target-obj.offsetWidth)/10;
??????????? speed=speed>0?Math.ceil(speed):Math.floor(speed);
??????????? obj.timer=setInterval(function(){
??????????????? if(obj.offsetWidth==target){
??????????????? clearInterval(obj.timer);
??????????? }else{
??????????????? obj.style.width=obj.offsetWidth+speed+'px';
??????????? }
?? ?
??????????? },30)
??????????? }
??? </script>
??? <body>
??????? <ul>
??????????? <li></li>
??????????? <li></li>
??????????? <li></li>
??????????? <li></li>
??????? </ul>
??? </body>
</html>
2017-09-18
用控制臺查了一下,你的speed 是不變的,這樣的話,if(obj.offsetWidth==target)有可能永遠都不滿足,例如:用速度9從兩百運動到400,會剛好錯過400這個值,計時器就一直沒被清除。
解決方法:
把speed的計算放進setInterval里面的那個參數下
代碼:
? ? ? ? function startMove(obj,target){
??????????? clearInterval(obj.timer);
??????????? obj.timer=setInterval(function(){
? ? ? ? ? ? var speed=(target-obj.offsetWidth)/10;
??????????? speed=speed>0?Math.ceil(speed):Math.floor(speed);????????????????
????????????if(obj.offsetWidth==target){
??????????????? clearInterval(obj.timer);
??????????? }else{
??????????????? obj.style.width=obj.offsetWidth+speed+'px';
??????????? }
?? ?
??????????? },30)
??????????? }
2017-09-15
感覺沒啥地方出錯啊,要不你去看下源碼吧