nodebook/20191018/offset.html
2019-10-19 15:25:41 +08:00

62 lines
1.5 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
height: 300px;
width: 300px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<input type="button" value="移动到400px" id='btn1'>
<input type="button" value="移动到800px" id='btn2'>
<div id="dv"></div>
<script type="text/javascript">
window.onload = function() {
var btn1 = document.getElementById('btn1')
var dv = document.getElementById('dv')
var timer1;
btn1.onclick=function() {
var current = dv.offsetLeft
var step = 10
timer1 = setInterval(function(){
current += step;
//先判断后赋值
if(current >= 400) {
clearInterval(timer1)
current = 400
}
dv.style.left = current + 'px';
}, 10)
}
var btn2 = document.getElementById('btn2')
var timer2;
btn2.onclick=function() {
var current = dv.offsetLeft
var step = 10
timer2 = setInterval(function(){
current += step;
//先判断后赋值
if(current >= 800) {
clearInterval(timer2)
current = 800
}
dv.style.left = current + 'px';
}, 10)
}
}
</script>
</body>
</html>