執(zhí)行下面代碼后不知道為什么打開(kāi)游覽器只能正常運(yùn)行一次第二次就開(kāi)始亂飄了!
<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<head>
<title>速度</title>
<link rel="stylesheet" type="text/css" href="定時(shí)器.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);
}
2015-11-04
<!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>
2015-12-23
我想問(wèn)問(wèn),為什么在一個(gè)計(jì)時(shí)器開(kāi)始之前,就清除啊,clearInterval(timer);就是這句
2015-11-04
相對(duì)定位使用錯(cuò)誤。將.div1樣式中的display:relative 改為display:absolute就可以了。
詳解:相對(duì)定位元素會(huì)相對(duì)于它在正常流中的默認(rèn)位置偏移。
所以你第一次,執(zhí)行的時(shí)候是正常。第二次的時(shí)候它參照物發(fā)生了變化。不再是文檔剛加載完畢時(shí)的位置。
2015-11-04
沒(méi)有清楚默認(rèn)的。。。所以就會(huì)出現(xiàn)72的來(lái)。所以應(yīng)在css中加margin:0;padding:0;這個(gè)一抖一抖的,或者你這種情況的,一般都是數(shù)字不對(duì)導(dǎo)致的。。你看到那個(gè)alert()沒(méi)有,如果沒(méi)有加的話會(huì)是72,就是瀏覽器幫你添加的。。。。。我上面的代碼,親測(cè)沒(méi)有問(wèn)題??!