為啥鼠標(biāo)上下來(lái)回滾動(dòng)時(shí)候,li消失,或者無(wú)限制的增加,是瀏覽器運(yùn)行比較卡,還是代碼問(wèn)我。
<!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
用控制臺(tái)查了一下,你的speed 是不變的,這樣的話,if(obj.offsetWidth==target)有可能永遠(yuǎn)都不滿足,例如:用速度9從兩百運(yùn)動(dòng)到400,會(huì)剛好錯(cuò)過(guò)400這個(gè)值,計(jì)時(shí)器就一直沒(méi)被清除。
解決方法:
把speed的計(jì)算放進(jìn)setInterval里面的那個(gè)參數(shù)下
代碼:
? ? ? ? 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
感覺(jué)沒(méi)啥地方出錯(cuò)啊,要不你去看下源碼吧