
水平移动分析:
可看成是一个物体的左边距变化。
比如:向右移动是左边距越来越大(数值为正),可调整物体的左边距来实现
向左移动是左边距越来越小(数值为负),可调整物体的左边距来实现
实际代码如下:
<style>
*{padding: 0;margin: 0px;}
#box{width: 100px;height: 100px;border-radius: 50%;background: red;position: absolute;top: 50px;left: 0;}
</style>
<body>
<button id="btn">向右</button>
<button id="btn1">向左</button>
<div id="box"></div>
<script>
var box=document.getElementById('box');
//速度
var index=10;
//定时器编号
var b;
//添加向右点击事件
document.getElementById('btn').onclick=function(){
clearInterval(b);//清除上一个定时器执行的事件
b=setInterval(getMove,100,index);//每100毫秒执行一次getMove函数
}
//添加向左点击事件
document.getElementById('btn1').onclick=function(){
clearInterval(b);//清除上一个定时器执行的事件
b=setInterval(getMove,100,-index);//每100毫秒执行一次getMove函数
}
//box移动位置
function getMove(index){
//获取box的左距离
var a=window.getComputedStyle(box,null).left;
a=parseInt(a);//转换为数值
box.style.left=a+index+'px'//计算box的左距离
}
</script>
</body>垂直移动分析:
可看成是一个物体的上边距变化。
比如:向下移动是上边距越来越大(数值为正),可调整物体的上边距来实现
向上移动是上边距越来越小(数值为负),可调整物体的上边距来实现
实际代码如下:
<style>
*{padding: 0;margin: 0px;}
#box{width: 100px;height: 100px;border-radius: 50%;background: red;position: absolute;top: 50px;left: 0;}
</style>
<body>
<button id="btn">向下</button>
<button id="btn1">向上</button>
<div id="box"></div>
<script>
var box=document.getElementById('box');
//速度
var index=10;
//定时器编号
var b;
//添加向下点击事件
document.getElementById('btn').onclick=function(){
clearInterval(b);//清除上一个定时器执行的事件
b=setInterval(getMove,100,index);//每100毫秒执行一次getMove函数
}
//添加向上点击事件
document.getElementById('btn1').onclick=function(){
clearInterval(b);//清除上一个定时器执行的事件
b=setInterval(getMove,100,-index);//每100毫秒执行一次getMove函数
}
//box移动位置
function getMove(index){
//获取box的上距离
var a=window.getComputedStyle(box,null).top;
a=parseInt(a);//转换为数值
box.style.top=a+index+'px'//计算box的上距离
}
</script>
</body>相关教程推荐:js教程
以上就是如何利用js实现水平移动与垂直移动效果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号