- 用JS实现最简单的动画,用
setInterval(fun(),milltime);
其中fun()是每隔milltime毫秒执行一次的函数。 - 以下是简陋效果图,当鼠标在分享位置上时,红色div将从浏览器边上慢慢向右展示,当鼠标离开分享位置时,红色div将慢慢向左隐藏
- 详细代码:
<body>
<div id="div1" >
<span id="share">分享</span>
</div>
</body>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
div{
width: 200px;
height: 200px;
background-color: #f00;
position: relative;
left: -200px;
}
span{
width: 30px;
height: 50px;
background-color: aqua;
position: absolute;
top: 70px;
left: 200px;
text-align: center;
}
</style>
<script type="text/javascript">
var div1 = document.getElementById("div1");
var share = document.getElementById("share");
var timer = null;
var speed = 0;
div1.onmouseover = function(){
startMove(0);
}
div1.onmouseout = function(){
startMove(-200);
}
var startMove = function(target) {
if(target >= 0){
speed = 10;
}else {
speed = -10;
}
clearInterval(timer);
timer = setInterval(function () {
if(div1.offsetLeft == target){
clearInterval(timer);
}else {
div1.style.left = div1.offsetLeft + speed + "px";
}
}, 30);
}
</script>