跑起來了,但是為什么沒有停下來?。壳缶劝?,求救。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
? ? ?#div1{
? ? ? width: 200px;
? ? ? height: 80px;
? ? ? ? background-color: #c22;
? ? ? ? position: relative;
? ? ? ? left: -200px;
? ? ? ? top: 0px;
? ? ?}
? ? #div1 span{
? ? ?width: 20px;
? ? ?height: 20px;
? ? ?background-color: blue;
? ? ?position: absolute;
? ? ?left: 200px;
? ? ?top: 30px;
? ? }
</style>
<script>
window.onload = function(){
? ? ? ? ?var odiv= document.getElementById('div1');
? ? ? ? ?odiv.onmouseover=function(){
? ? ? ? ? ?startmove();
? ? ? ? ?}
? ? ? ? ?
}
?var timer = null;
?function startmove(){
? ? clearInterval(timer)
?var odiv = document.getElementById('div1');
? timer = setInterval(function(){
? if(odiv.offsetLeft == 100){
? ? ? ?clearInterval(timer);
? }
? else{
? odiv.style.left = odiv.offsetLeft+10+'px';
? }
? ?
? },30)
?}
</script>
</head>
<body>
<div id="div1"><span></span></div>
</body>
</html>
2016-03-16
你沒有清除樣式,也就是加上這段*{margin:0;padding:0;}。導致你div的left并不等于200這個整數(shù),導致你后面odiv.style.left = odiv.offsetLeft+10+'px';時,至直接跳過了odiv.offsetLeft == 100這個數(shù),從而使得你的程序停不下來,你可以先把
if(odiv.offsetLeft == 100){
? ? ? ?clearInterval(timer);
? }
修改為
if(odiv.offsetLeft <= 100){
? ? ? ?clearInterval(timer);
? }
自己看下最后的odiv.offsetLeft等于多少。
修改以后的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}
? ? ?#div1{
? ? ? width: 200px;
? ? ? height: 80px;
? ? ? ? background-color: #c22;
? ? ? ? position: relative;
? ? ? ? left: -200px;
? ? ? ? top: 0px;
? ? ?}
? ? #div1 span{
? ? ?width: 20px;
? ? ?height: 20px;
? ? ?background-color: blue;
? ? ?position: absolute;
? ? ?left: 200px;
? ? ?top: 30px;
? ? }
</style>
<script>
window.onload = function(){
? ? ? ? ?var odiv= document.getElementById('div1');
? ? ? ? ?odiv.onmouseover=function(){
? ? ? ? ? ?startmove();
? ? ? ? ?}
? ? ? ? ?
}
?var timer = null;
?function startmove(){
? ? clearInterval(timer)
?var odiv = document.getElementById('div1');
? timer = setInterval(function(){
? if(odiv.offsetLeft == 0){
? ? ? ?clearInterval(timer);
? }
? else{
? odiv.style.left = odiv.offsetLeft+10+'px';
? alert(odiv.offsetLeft);
? }
? ?
? },30)
?}
</script>
</head>
<body>
<div id="div1"><span></span></div>
</body>
</html>
2016-04-21
啊!看看問答,自己的問題就解決了!真棒!調(diào)了倆小時都不知道為啥錯了。原來是初始化!
2016-04-17
回找了半天,視頻翻過去看的,一直沒找到原因,倒是注意到自己沒初始化了,但沒覺得會有影響。沒想到問題出在那兒了,還是得細心啊
2016-03-31
樓上正解