js之封装函数实现元素的左右来回移动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
div {
position: absolute;
left: 0px;
width: 200px;
height: 200px;
background: greenyellow;
}
</style>
<script src="./getby.js"></script>
<script type="text/javascript">
window.onload = function() {
var btnS = document.getElementsByTagName('button');
var div = document.querySelector('div');
btnS[0].onclick = function(){
move(div,1000,10);
}
btnS[1].onclick = function(){
move(div,0,10);
}
}
</script>
</head>
<body>
<button type="button">去吧</button>
<button type="button">回来</button>
<div></div>
</body>
</html>
getby.js
/* Created By dyh 2020.3.28 */
//获取任意元素的非行内样式 用法:getStyle(元素,属性);
function getStyle(ele, attr){
if (ele.currentStyle == undefined) {
//标准浏览器
var bg = getComputedStyle(ele)[attr];
return bg;
} else {
//ie8-
var bg = ele.currentStyle[attr];
return bg;
}
}
//封装一个函数,用来执行任意元素正反两个方向的动画 用法:move(元素,终点,步长);
var timer = null; //定时器id
function move(ele, end, step) {
//清除定时器防止叠加
clearInterval(timer);
//获取起点
var start = parseInt(getStyle(ele, 'left'));
//处理步长 判断向前 向后
if (end > start) {
step = step;
} else if (end < start) {
step = -step;
}
//定时器
timer = setInterval(function() {
//计算下一步落点
start += step;
//重点结束
if (start >= end && step > 0) {
//正向移动
start = end;
clearInterval(timer);
} else if (start <= end && step < 0) {
//负方向移动
start = end;
clearInterval(timer);
}
ele.style.left = start + 'px';
}, 20);
}

本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634800.html

浙公网安备 33010602011771号