这个淡入淡出的效果非常的简单,大致效果就是我们划过去时,颜色变深,当移出时颜色变淡有些类似渐变效果。
如果想要好看的样式和效果的话可以多看一些效果类的js文章对学习基础js有很大的帮助的。
那么,我们献上效果图,看一下我们心中想要的效果吧!
我会把html,css样式复制在这里,
我把重点讲述在js上。
那么,先献上我们的css和HTML的样式和架构吧!
.box>div{
width:200px;
height:200px;
background-color:#000;
opacity:0.4;
float: left;
margin:0 30px;
}
<div class="box">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
接下来,重点来了!
就是我们的js效果,js我们要用到移入onmouseover和移出onmouseout还有一个清除间歇调用onmouseout。
var oBox = document.querySelector(".box").children;
for(var i = 0; i < oBox.length; i++){
oBox[i].timer = null;
oBox[i].onmouseover = function(){
Move(this,100)
}
oBox[i].onmouseout = function(){
Move(this,40)
}
}
function Move(dom,target){
clearInterval(dom.timer)
dom.timer = setInterval(function(){
var op = parseInt(getStyle(dom,"opacity") * 100);//通过设置透明度
var spead = (target - op) / 6;
spead = spead < 0 ? Math.floor(spead) : Math.ceil(spead);
if(op == target){
clearInterval(dom.timer)
}else{
dom.style.opacity = (op + spead) / 100;
}
},100)
}
function getStyle(elem, attr){ //获取非行间样式
if(window.getComputedStyle){
return getComputedStyle(elem, null)[attr];
}else{
return elem.currentStyle[attr];
}
}
这样我们就可以轻轻松松实现一个淡入淡出的效果啦!