Javascript的offsetleft取值問題


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0;
padding: 0;
}

.big {
width: 800px;
height: 100px;
border: 1px solid #000;
position: absolute;
left: 100px;
top: 100px;
/*margin: 50px auto;*/
}

.box {
position: absolute;
top: 0;
left:0;
width: 100px;
height: 100px;
background-color: pink;
margin: 0 -1px;
}
</style>
</head>
<body>

<button>向右移動2個盒子距離</button>
<button>向左移動2個盒子距離</button>
<div class="big">
<div class="box"></div>
</div>

<script>
var btnArr = document.querySelectorAll('button');
var big = document.getElementsByClassName('big')[0];
var box = document.querySelector('.box');
var width = box.offsetWidth;
console.log(width);

var count=0;

btnArr[0].onclick = function () {
// alert();
count++;
animate(box,-count*width);
}

btnArr[1].onclick = function () {
count--;
animate(box,-count*width);
}

//緩動框架封轉
function animate(ele,target) {
clearInterval(ele.timer);
ele.timer = setInterval(function () {
var step = (target-ele.offsetLeft)/10;
step=step>0?Math.ceil(step):Math.floor(step);
ele.style.left = ele.offsetLeft + step +'px';
if(Math.abs(target-ele.offsetLeft)<=Math.abs(step)){
ele.style.language = target+'px';
clearInterval(ele.timer);
}
console.log(1);
},31);
}
</script>
</body>
</html>


這樣給要移動的元素加上margin之后,不能判斷清除定時器的條件,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM