如何在hover js上的3个类之间切换
How to toggle between 3 classes on hover js
我有一个无序的列表,里面有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);
最终结果,不起作用。。
On"mouseover"根据需要将类设置为"stateOff"或"stateHovered"。然后在"mouseout"中,将它们设置回"color"。如果你可以使用jQuery,它是相当直接的,尽管我认为你可能会想摆弄一下CSS:
$(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');
});
});
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;
}
<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>
相关文章:
- 如何在javascript中获取两个日期之间的周六和周日的日期
- 在Google Analytics中跟踪用户,但只能在两个操作之间跟踪
- 如何在两个不同的iframe HTML之间进行通信
- 有效地获取两个区间之间的随机整数
- 如何用moment.js列出两个日期之间的所有月份
- jQuery在两个字符串标识符之间选择HTML
- 定时循环,使用Javascript在2个循环之间间隔x秒
- JavaScript中的RegEx:两个标签之间的内容
- moment.js在两个时区格式的日期之间存在差异
- Javascript-如何使用bootstrap日期时间选择器自动计算两个时间输入之间的差异
- 计算HTML表TD中两个数字之间的百分比
- 用时间戳获取两个不同日期之间的时间差
- 通过共享服务在两个不同ng应用程序中的控制器之间共享数据
- 如何在jQuery中获取两个事件之间的时间差
- 通过node.js和socket.io在两个用户之间发送消息
- JavaScript函数,用于计算两个日期之间的年、月和天数
- 有没有一种方法可以从两个标签之间提取文本,并以我选择的格式输出
- 在两个多选字段之间移动选项
- 通过变量在两个数字之间切换
- 如何在Protractor中比较两个窗口之间两个元素的值