亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

執行下面代碼后不知道為什么打開游覽器只能正常運行一次第二次就開始亂飄了!

<!DOCTYPE html>

<html>

<meta charset="utf-8"/>

<head>

<title>速度</title>

<link rel="stylesheet" type="text/css" href="定時器.css">

<script src="速度.js"></script>

</head>

<body>

<div class="div1" id="div1">

<span class="div0">速度</span>

</div>

</body>

</html>

//css

.div1{

width:80px;

height: 80px;

position: relative;

background-color: red;

left: -80px;

}

.div0{

position: absolute;

left: 80px;

background-color: blue;

width: 20px;

height: 40px;

top: 20px;

font-size: 10px;


}

//js

window.onload=function(){

var tanchu=document.getElementById('div1');

tanchu.onmouseover=function(){

startMove(10,0);

}

tanchu.onmouseout=function(){

startMove(-10,-70);

}

}

var timer=null;

function startMove(speed,itarget){

clearInterval(timer);

var tanchu=document.getElementById('div1');

timer=setInterval(function(){

if(tanchu.offsetLeft==itarget){

clearInterval(timer);

}

else

{

tanchu.style.left=tanchu.offsetLeft+speed+'px';

}},3);

}


正在回答

4 回答

<!DOCTYPE html>

<html>

<meta charset="utf-8"/>

<head>

<title>速度</title>

<style type="text/css">

body{

margin: 0;

padding: 0;

}

.div1{

width:80px;

height: 80px;

position: relative;

background-color: red;

left: -80px;

}

.div0{

position: absolute;

left: 80px;

background-color: blue;

width: 20px;

height: 40px;

top: 20px;

font-size: 12px;


}

</style>


</head>

<body>

<div class="div1" id="div1">

<span class="div0">速度</span>

</div>

</body>

<script type="text/javascript">

var timer=null;

window.onload=function(){

var tanchu=document.getElementById('div1');

// alert(tanchu.offsetLeft);//彈出的是72.。。所以和你想的有天差地別

tanchu.onmouseover=function(){

startMove(10,0);

}

tanchu.onmouseout=function(){

startMove(-10,-70);

}

}


function startMove(speed,itarget){

clearInterval(timer);

var tanchu=document.getElementById('div1');

timer=setInterval(function(){

if(tanchu.offsetLeft==itarget){

clearInterval(timer);

}

else

{

tanchu.style.left=tanchu.offsetLeft+speed+'px';

}},10);

}


</script>

</html>


0 回復 有任何疑惑可以回復我~
#1

BAYBAZC 提問者

非常感謝!
2015-11-04 回復 有任何疑惑可以回復我~
#2

譚譚譚 回復 BAYBAZC 提問者

下面那個仁兄說的也對,我試過了的
2015-11-04 回復 有任何疑惑可以回復我~

我想問問,為什么在一個計時器開始之前,就清除啊,clearInterval(timer);就是這句

0 回復 有任何疑惑可以回復我~

相對定位使用錯誤。將.div1樣式中的display:relative 改為display:absolute就可以了。

詳解:相對定位元素會相對于它在正常流中的默認位置偏移。

所以你第一次,執行的時候是正常。第二次的時候它參照物發生了變化。不再是文檔剛加載完畢時的位置。

0 回復 有任何疑惑可以回復我~

沒有清楚默認的。。。所以就會出現72的來。所以應在css中加margin:0;padding:0;這個一抖一抖的,或者你這種情況的,一般都是數字不對導致的。。你看到那個alert()沒有,如果沒有加的話會是72,就是瀏覽器幫你添加的。。。。。我上面的代碼,親測沒有問題??!

0 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

執行下面代碼后不知道為什么打開游覽器只能正常運行一次第二次就開始亂飄了!

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號