描述:我们想要达到的效果是,当鼠标移入 ‘提示’ 框的时候,左侧的 div显示到固定位置,移出回到原始位置。
1.首先我们需要了解的是 js的鼠标移入事件: (不论鼠标指针穿过被选元素或其子元素,都会触发)
onmouseover : 移入
onmouseout : 移出
了解一下:
mouseenter :只有在鼠标指针穿过被选元素时,才会触发
mouseleave : 只有在鼠标指针离开被选元素时,才会触发
页面布局:
<style>
*{padding: 0;margin: 0;}
.box1{width: 200px;height: 200px;background-color: antiquewhite;position: relative;top: 25px;left: -200px;}
.msg{display: inline-block;width: 25px;height: 80px;text-align: center;position: absolute;left: 200px;line-height: 40px;background-color: #3d9090;color: white; }
</style>
<div class="box1" id='box1'>
this is a message;
<span class="msg" >提示</span>
</div>
js部分:
var oDiv = document.getElementById('box1');
oDiv.onmouseover = function(){
startmove(0)
}
oDiv.onmouseout = function(){
startmove(-200)
}
var timer = null;
function startmove(iTager){
clearInterval(timer);
var speed =0;
if(oDiv.offsetLeft > iTager){
speed = -10;
}else{
speed = 10;
}
timer = setInterval(function(){
if( oDiv.offsetLeft == iTager){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
},30)
}
切记,在事件触发之前先清除定时器,目的是为了避免鼠标不断移入的过程中, speed 速度值不断增大;