本文摘自PHP中文网,作者V,侵删。

水平移动分析:
可看成是一个物体的左边距变化。
比如:向右移动是左边距越来越大(数值为正),可调整物体的左边距来实现
向左移动是左边距越来越小(数值为负),可调整物体的左边距来实现
实际代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <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);
}
document.getElementById( 'btn1' ).onclick= function (){
clearInterval(b);
b=setInterval(getMove,100,-index);
}
function getMove(index){
var a=window.getComputedStyle(box, null ).left;
a=parseInt(a);
box.style.left=a+index+ 'px'
}
</script>
</body>
|
垂直移动分析:
可看成是一个物体的上边距变化。
比如:向下移动是上边距越来越大(数值为正),可调整物体的上边距来实现
向上移动是上边距越来越小(数值为负),可调整物体的上边距来实现
实际代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <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);
}
document.getElementById( 'btn1' ).onclick= function (){
clearInterval(b);
b=setInterval(getMove,100,-index);
}
function getMove(index){
var a=window.getComputedStyle(box, null ).top;
a=parseInt(a);
box.style.top=a+index+ 'px'
}
</script>
</body>
|
相关教程推荐:js教程
以上就是如何利用js实现水平移动与垂直移动效果的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
网站对联广告js代码分享
js+html5实现页面可刷新的倒计时效果
简述什么是ajax
github不用jq用什么
js中隐藏元素用什么方法
html实现自动清理js、css文件的缓存
js干货分享―-this指向问题
js 怎么判断数字相等
javascript如何删除键值对
前端工程师需要掌握哪些知识?
更多相关阅读请进入《js》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 如何利用js实现水平移动与垂直移动效果