1.分享菜单案例
/*
鼠标移入
-100 => 0
鼠标移出
0 => -100
*/
var oDiv = document.getElementById("div1");
oDiv.onmouseover = function(){
startMove();
}
oDiv.onmouseout = function(){
startMove2();
}
var timer = null;
function startMove(){
var oDiv = document.getElementById("div1");
var speed = 5;
clearInterval(timer);
timer = setInterval(function(){
//运动和停止
if(oDiv.offsetLeft==0){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + speed + "px";
}
},30);
}
function startMove2(){
var oDiv = document.getElementById("div1");
var speed = -5;
clearInterval(timer);
timer = setInterval(function(){
//运动和停止
if(oDiv.offsetLeft==-100){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + speed + "px";
}
},30);
}
相同代码合并
/*
鼠标移入
-100 => 0
鼠标移出
0 => -100
*/
var oDiv = document.getElementById("div1");
oDiv.onmouseover = function(){
startMove(0);
}
oDiv.onmouseout = function(){
startMove(-100);
}
var timer = null;
function startMove(iTag){
var oDiv = document.getElementById("div1");
var speed = 5;
//判断当前值距离与目的值
if(oDiv.offsetLeft>iTag){
speed = -Math.abs(speed);
}else {
speed = Math.abs(speed);
}
clearInterval(timer);
timer = setInterval(function(){
//运动和停止
if(oDiv.offsetLeft==iTag){
clearInterval(timer);
}else{
oDiv.style.left = oDiv.offsetLeft + speed + "px";
}
},30);
}
2、淡入淡出效果
var oImg = document.getElementById("img1");
oImg.onmouseover = function(){
//30 => 100
startMove(100);
}
oImg.onmouseout = function(){
//100 => 30
startMove(30);
}
//设置一个中间变量为透明度的当前值
var alpha = 30;
function startMove(iTarget){
var oImg = document.getElementById("img1");
var timer = null;
clearInterval(timer);
var speed = 2;
speed = iTarget > alpha ? Math.abs(speed):-Math.abs(speed);
timer = setInterval(function(){
if(iTarget==alpha){
clearInterval(timer);
}else{
alpha += speed;
//重新设置透明度
oImg.style.opacity = alpha / 100;
oImg.style.filter = `alpha(opacity=${alpha})`;
}
},30)
}