您的位置:首页 > 其它

文章标题

2017-10-27 11:34 134 查看
<head>
<meta charset="UTF-8">
<title></title>
</head>

<style>
button {
left: 0;
}

div {
width: 50px;
height: 50px;
background: red;
position: absolute;
top: 120px;
left: 20px;
}
</style>

<body>

<!--<button class="up">向前</button>
<button class="back">向后</button>

<div class="Div1"></div>
<script>
var up = document.querySelector('.up');
var back = document.querySelector('.back');
var Div1 = document.querySelector('.Div1');
var timer = null;

up.onclick = function() {
doMove(Div1,'top',17,800,function(){
doMove(Div1,'top',17,120)
});
};
back.onclick = function() {
doMove(Div1,'top',17,120);
};

//抖动封装
function doMove(obj,dirc,step,target,fn){

clearInterval(timer);
//判断目标值和当前值大小,以判断方向
step = target > parseInt(getstyle(obj, dirc)) ? step : -step;

timer = setInterval(function() {
var pos = parseInt(getstyle(obj, dirc)) + step;
if(pos >= target && step > 0 || pos <= target && step < 0) {
pos = target;
clearInterval(timer);
fn&&fn();

};
obj.style[dirc] = pos + 'px';
}, 20);
}

//获取元素值
function getstyle(obj, attr) {
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}
</script>-->

<!--<script>
var flag = true;
document.onclick = function(){
flag = !flag; //这样可以转化布尔值, 这样转化不了flag != flag
console.log(flag)
}
</script>-->

<script type="text/javascript">
var str = '';
var num = 20;
var index = 0;
var divs = document.getElementsByTagName('div');
var setim = null;
var onoff = true;

for(var i = 1; i < num; i++) {
str += '<div style="left:' + i * 60 + 'px"></div>';
};

document.body.innerHTML = str;

document.onclick = function() {

var This = this;

clearInterval(This.setim);

This.setim = setInterval(function() {

if(onoff) {
doMove(divs[index], 'top', 20, 800);
} else {
doMove(divs[index], 'top', 20, 120);
}

index++;

if(index == divs.length) {
clearInterval(This.setim);
index = 0;
onoff = !onoff; //等下落的元素都完毕,修改开关
};
}, 50);
}

//抖动封装
function doMove(obj, dirc, step, target, fn) {
clearInterval(obj.timer);
//判断目标值和当前值大小,以判断方向
step = target > parseInt(getstyle(obj, dirc)) ? step : -step;

obj.timer = setInterval(function() {
var pos = parseInt(getstyle(obj, dirc)) + step;
if(pos >= target && step > 0 || pos <= target && step < 0) {
pos = target;
clearInterval(obj.timer);//此处表明该效果执行完毕
fn && fn();//判断有没有,回调函数,然后执行
};
obj.style[dirc] = pos + 'px';
}, 20);
}

//获取元素值
function getstyle(obj, attr) {
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}
</script>

</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: