如何在悬停js上的3个类之间切换

时间:2015-03-26 02:26:38

标签: javascript html css

我有一个无序列表,里面有4个项目。 在鼠标悬停时,它应该增长到ul的宽度的100%,并且所有'名词悬停的li'应缩小到0%宽度。 当鼠标离开时,它们都应该恢复到25%宽度的初始状态。 类似的东西:

<ul id="menu2">
  <li class="color"></li>
  <li class="color"></li>
  <li class="color"></li>
  <li class="color"></li>
</ul>

CSS

#menu2{
overflow: hidden;
padding-left: 0;
padding-right: 0;
margin: 0;
}
.color{
display: inline-block;
position: relative;
list-style: none;
float: left;
height: 110px;
margin-right: 0;
width: 25%;
background-color: blue;
cursor: pointer;
}

.stateHovered{
    width: 100%;
    transition: all 500ms ease-out;
    background-color: #FAA500;
}
.stateOff{
    width: 0;
}

js

function addListeners(){
document.getElementById('menu2').children.addEventListener("mouseover", toggleClassFunction);
    function toggleClassFunction() {
        for(i = 0; i < menu2.length; i++) {
            if(menu2[i] !=this) {
                menu2[i].className = "stateOff";
            }else if(menu2[i] === this){
                menu2[i].className = "stateHovered";
            }else {
                menu2[i].className = "color";
                }
        }
    }   
}
window.addEventListener("load", addListeners);

最终结果,不起作用..

1 个答案:

答案 0 :(得分:0)

On&#34; mouseover&#34;将类设置为&#34; stateOff&#34;或者&#34; stateHovered&#34;如所须。然后在&#34; mouseout&#34;将它们设置回&#34; color&#34;。如果你可以使用jQuery,它是相当直接的,虽然我认为你可能会想要稍微摆弄一下CSS:

&#13;
&#13;
$(document).ready(function(){
    $('#menu2 li').mouseover(function(){
        //Instead of trying to figure out who is who, just set them all to "stateOff"
        $('#menu2 li').attr('class','stateOff');
      
        //Then set "this" to "stateHovered".
        $(this).attr('class','stateHovered');
      
        //The browser won't render any changes until the script finishes running,
        //So you don't have to worry about "this" jumping back and forth between
        //two styles.
    });
    
    
    $('#menu2 li').mouseout(function(){
        $('#menu2 li').attr('class','color');
    });
});
&#13;
menu2{
overflow: hidden;
padding-left: 0;
padding-right: 0;
margin: 0;
}
.color{
display: inline-block;
position: relative;
list-style: none;
float: left;
height: 110px;
margin-right: 0;
width: 25%;
background-color: blue;
cursor: pointer;
}

.stateHovered{
    width: 100%;
    transition: all 500ms ease-out;
    background-color: #FAA500;
}
.stateOff{
    width: 0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu2">
  <li class="color">A</li>
  <li class="color">B</li>
  <li class="color">C</li>
  <li class="color">D</li>
</ul>
&#13;
&#13;
&#13;