1 简单运动(匀速)
box{
width: 100px;
height: 100px;
background-color: #ccc;
position: absolute;
top:200px;
left: 0;
}
<script type="text/javascript">
var obtn = document.querySelector('button');
var obox = document.querySelector('.box');
// 设置速度
var speed = 10;
obtn.onclick=function(){
// 1 先清除掉定时器
clearInterval(obox.timer);
obox.timer = setInterval(function(){
obox.style.left = obox.offsetLeft + speed + 'px'
},30);
}
</script>
2 指定运动的距离(匀速)
js代码:
<script type="text/javascript">
var obtn = document.querySelector('button');
var obox = document.querySelector('.box');
var totalDistance = 500;
// 设置速度
var speed = 10;
obtn.onclick = function() {
// 1 先清除掉定时器
clearInterval(obox.timer);
obox.timer = setInterval(function() {
obox.style.left = obox.offsetLeft + speed + 'px'
if(getStyle(obox,'left') >= totalDistance){
// 已经到达目的地了
obox.style.left = totalDistance + 'px';
// 同时我们还需要清除掉定时器
clearInterval(obox.timer);
}
}, 30);
}
// 封装获取样式的方法 不带px单位的
function getStyle(ele, style) {
let result = ele.currentStyle ? ele.currentStyle[style] : getComputedStyle(ele, null)[style];
return parseInt(result);
}
</script>
3 缓冲运动(速度由快到慢,直至停止)
缓冲运动的原理: 速度由距离决定。即: 距离越大速度越大,距离越近,速度越小,直至为0.
4 加速运动(速度由慢到快,直至到达终点)
加速运动和缓冲运动相反,代码也不需要做过多的修改
原理:根据移动的距离来设置速度,也就是正比关系
var obtn = document.querySelector('button');
var obox = document.querySelector('.box');
var totalDistance = 500;
// 设置速度
var speed = null;
obtn.onclick = function() {
// 1 先清除掉定时器
clearInterval(obox.timer);
obox.timer = setInterval(function() {
// 1 获取当前运动的距离
var curPosition = getStyle(obox,'left');
// 2 speed是变化的 动态计算
speed = (curPosition / 10)||1;
// 对speed进行取整操作
// ceil:向上取整
// floor: 向下取整
// 3 *需要对speed进行取整 否则达不到临界值
speed = speed > 0? Math.ceil(speed):Math.floor(speed);
obox.style.left = obox.offsetLeft + speed + 'px';
console.log(speed);
if(getStyle(obox,'left') >= totalDistance){
console.log('我执行了没');
obox.style.left = totalDistance + 'px';
clearInterval(obox.timer);
}
}, 30);
}
// 封装获取样式的方法 不带px单位的
function getStyle(ele, style) {
let result = ele.currentStyle ? ele.currentStyle[style] : getComputedStyle(ele, null)[style];
return parseInt(result);
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。