水平位移动画能用在很多地方,如滚动巨幕,公告更迭等。具体效果及代码如下。
代码如下
样式部分
div {
position: fixed;
width: 100px;
height: 100px;
background-color: yellow;
left: 0;
top: 100px;
}
主体部分
<input type="text">
<div>
</div>
JS部分
<script>
window.onload = function (dom, target) {
var input = document.querySelector('input')
var div = document.querySelector('div')
div.onclick = function () {
animate(div, input.value);
console.log(input.value);
}
function animate(dom, target) {
clearInterval(dom.timer)
console.log("dom.timer",dom.timer);
dom.timer = setInterval(function () {
var nowLeft = dom.offsetLeft;
var need = (target - dom.offsetLeft)/10;
need = need > 0?Math.ceil(need) : Math.floor(need);
// (var need = nowLeft< target ? 3 : -3;
// console.log(need);)
var targetLeft = nowLeft + need;
// console.log(targetLeft);
dom.style.left = targetLeft + "px";
if (Math.abs(targetLeft - target) <= Math.abs(need)) {
clearInterval(dom.timer);
console.log('结束定时器');
dom.style.left = target + "px";
}
}, 50)
}
}
</script>
<script>
//window.onload使JS可位于主体后
window.onload = function (dom, target) {
//获取input和div节点
var input = document.querySelector('input')
var div = document.querySelector('div')
//为div添加点击事件
div.onclick = function () {
//调用animate(div,input,value)事件
animate(div, input.value);
// console.log(input.value);
}
//animate事件
function animate(dom, target) {
//清除dom.timer计时器
clearInterval(dom.timer)
console.log("dom.timer",dom.timer);
//dom.timer计时器
dom.timer = setInterval(function () {
//获取初始位置
var nowLeft = dom.offsetLeft;
//目标位置-当前位置的差除以10得到每次移动的距离
var need = (target - dom.offsetLeft)/10;
//判断后为”每步长度“取整
need = need > 0?Math.ceil(need) : Math.floor(need);
//获取每次位移后的位置
var targetLeft = nowLeft + need;
dom.style.left = targetLeft + "px";
//Math.abs取整
//判断与目标距离小于或等于“每步长度”时直接抵达目标终点
if (Math.abs(targetLeft - target) <= Math.abs(need)) {
clearInterval(dom.timer);
console.log('结束定时器');
dom.style.left = target + "px";
}
//间隔50毫秒
}, 50)
}
}
</script>