1.运动函数的三要素(1.运动的对象 2运动的方向 3.目标值)
2 封装好的函数使用时直接传参调用即可
废话不多说,代码奉上。一枚小白,有点简陋勿喷
Html代码
<div id="box1">
<div id="box2"></div>
</div>
Style样式
/* 注意设置运动的对象时,必须设置定位:position */
#box1 {
width: 500px;
height: 500px;
position: relative;
border: 1px solid black;
}
#box2 {
width: 100px;
height: 100px;
position: absolute;
background-color: red;
}
Js代码
<script>
// 获取对象名
let obj = document.getElementById('box2')
console.log(obj)
//obj是运动对象,target是运动的方向与目标值对象
function move(obj, target) {
ele = obj
//设置定时器
let times = setInterval(function () {
//遍历对象的属性
for (attr in target) {
// 获取对象的实时运动位置
let tmp = parseInt(pos(ele, attr))
console.log(tmp)
// 设置对象的运动速度,目标位置减去实时位置
let speed = (target[attr] - tmp ) / 10
// console.log(speed)
ele.style[attr] = speed + tmp + 'px'
// console.log(ele.style.attr)注意当属性是变量时得用:对象名.style[变量名]
// 如果对象的实时位置与目标位置相等的话就停止定时器
if (tmp == target[attr]) {
clearInterval(times)
}
// 设置对象运动的位置
}
//遍历对象属性后可通过对象属性名获取属性值
}, 30) //人眼能识别的最大帧数为24帧,超过24帧就看不出差别了
}
// 获取对象实时运动位置的函数
function pos(obj, attr) {
// 注意style可以设置和获取行内样式,但是不能获取外部样式
// currentStyle和getComputedStyle可以获取外部样式,但是不能设置,存在兼容性问题
// return obj.style.left
if (obj.currentStyle) {
获取css的样式
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj)[attr]
}
}
//定义了函数要调用才能生效 函数名()
move(obj, {
left: 400
})
</script>
关于style以及其它获取样式的不同之处,可以参考这篇文章https://www.cnblogs.com/cythia/p/6721145.html
加油,又是努力敲代码的一天!