<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin: 0; padding: 0;}
#div1{
width: 100px;
height: 100px;
background-color: aquamarine;
position: absolute;
left: 0px;
top: 0px;
}
</style>
</head>
<body>
<div id="div1">
</div>
<script>
window.onload = function() {
// 简单的运动函数
var div = document.querySelector('#div1')
// div.onclick = () => {
// // 获取元素样式
// let curStyle = parseInt(getStyle(div,'left'))
// // 通过定时器控制运动
// let timeId = setInterval(() => {
// curStyle += 5
// if(curStyle >= 400) {
// clearInterval(timeId)
// }else{
// div.style.left = curStyle + 'px'
// }
// },20)
// }
// 封装一个获取元素样式的函数
function getStyle(ele,style){
try{
return window.getComputedStyle(ele)[style]
}catch(error){
return ele.currentStyle[style]
}
}
// 封装一个运动函数
function move(ele,attr,target) { // ele是元素, attr是属性, target是目标样式
// 获取元素样式
let curStyle = parseInt(getStyle(ele,attr))
// 通过定时器控制运动
let timeId = setInterval(() => {
curStyle += 5
if(curStyle >= target) {
clearInterval(timeId)
}else{
ele.style[attr] = curStyle + 'px'
}
},20)
}
// 使用封装函数
div.onclick = () => {
move(div,'left',400)
move(div,'top',400)
}
}
</script>
</body>
</html>
12-10
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交