作为javascript小白,经常看到别人的网页有图片匀速移动,或者其他比较炫的效果,比如说幻灯片等网页元素可以自由移动的效果,网页返回顶部,当鼠标点击某个元素,元素就自动跑动等等。羡慕不已,可是自己只会一些简单的JS,为了学习之,于是自己摸索了一番,首先是W3C上的HTML DOM setTimeout()让我完成了这个效果,我制作的效果可以点击这里:
https://blog.yeskn.com/uploads/js-to-move.html
代码摘录如下:
<html>
<head>
<meta charset=utf8 />
<script>
var mt=0,opc=0,mr=0,tr;
var time;
function move(){
if(mt<=500){
document.getElementById('cube').style.marginLeft=mt+'px';
document.getElementById('cube').style.opacity=opc;
if(opc<1) opc=opc+0.01;
mt=mt+5;
tr=mt;
}
else if(mr<=400){
document.getElementById('cube').style.marginTop=mr+'px';
mr=mr+5;
tt=mr;
}
else if(tr>=5){
document.getElementById('cube').style.marginLeft=tr+'px';
tr=tr-5;
}
else if(tt>=5){
document.getElementById('cube').style.marginTop=tt+'px';
tt=tt-5;
}
time=setTimeout("move()",10);
}
</script>
</head>
<body onload="move()">
<div style="position:absolute;width:300px;height:300px;background:pink;opacity=0;border-radius:10px;" id="cube" onclick="clearTimeout(time);"></div>
</body>
</html>
其中最重要的是使用了setTimeOut()
这个JS里的函数,然后求元素的左边距是style.marginLeft
,对应的还有style.marginRight
等其余的三个,而不是style.margin-left
,这一点要特别注意,并且还有一个有点坑的是,
document.getElementById('cube').style.marginLeft
这个方法求得的不是一个纯粹的数,因为这个长度是有单位的,所以,他的数据类型应该是一个字符串,赋值时需要使用数字+’px’这样的方式。
进阶教程可以查看W3C关于setInterval()
方法的说明:http://www.w3school.com.cn/htmldom/met_win_setinterval.asp
One thought on “用javascript使div自由移动”