j查询在悬停时更改背景
jQuery changing background on hover
我有这个代码
.html
<div id="addQuesion">
<ul id="aQul">
<li class="aQli"></li>
<li class="aQli"></li>
</ul>
</div>
我的jQuery是
jQuery
$(document).ready(function(){
$(".aQli").mouseover(function(){
});
$(".aQli").mouseout(function(){
});
});
我希望当将鼠标悬停在 li 上时,背景应该是红色的,在退出该 li 时,背景应该恢复为白色。 我该怎么做?
你必须使用 jQuery 吗?
更"正确"的方法是向类添加悬停样式。
.aQli:hover{
background-color: red;
}
有关示例,请参阅此处。 http://jsfiddle.net/maurice_butler/5q6QM/
你可以简化它以使用 .hover():
$(document).ready(function(){
$(".aQli").hover(function(){
$(this).css("background", "#F00");
},
function(){
$(this).css("background", "#FFF");
});
});
第一个函数用于鼠标悬停,第二个函数用于鼠标退出。 .css() 函数设置 CSS 属性,在本例中为悬停元素的背景色。
$(function(){
$(".aQli").on('mouseover', 'li', function(){ //using "on" for optimization
this.style.backgroundColor = 'red'; //native JS application
}).on('mouseout', 'li', function(){ //chain to avoid second selector call
this.style.backgroundColor = 'white'; //native JS application
})
});
我想出了两种使用jQuery的方法。一种方法是使用 jQuery 直接更改 css,使用 .css() 设置背景颜色。
//css
ul#aQul li{
display : inline-block;
padding : 5px;
margin : 5px;
}
//javascript use jQuery
$(document).ready(function(){
$(".aQli").mouseover(function(){
$(this).css({
"background-color" : "red",
"cursor" : "pointer"
});
});
$(".aQli").mouseout(function(){
$(this).css({
"background-color" : "transparent",
"cursor" : "default"
});
});
});
另一种方法是在发生悬停时使用jQuery添加特定的类属性,并且有一个特定的css规则来更改背景颜色。
//css, need to specify the state of hover
ul#aQul li.hover{ //li elements which have "hover" class
cursor:pointer;
background-color : red;
}
//javascript
$(document).ready(function(){
$(".aQli").mouseover(function(){
$(this).addClass("hover") //hover, add class "hover"
});
$(".aQli").mouseout(function(){
$(this).removeClass("hover"); //hover out, remove class "hover"
});
});
$(document).ready(function(){
$(".box").hover(function(){
$(this).css("background-image", "url(ENETR URL HERE)");
},
function(){
$(this).css("background", "#FFF");
});
});
.box{
width:200px;
height:200px;
border: 1px solid black;
}
<html>
<head>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="box">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
相关文章:
- 导航菜单-悬停时的背景行为怪异
- 鼠标悬停时如何居中放大背景图像
- DT数据表背景颜色为黑色,但仍有悬停和选择颜色
- "Ken Burns效应”;悬停背景图像
- 如何动画删除悬停后的背景
- 更改鼠标悬停时映射图像热点的背景
- 悬停在链接上时不断更改背景图像
- 如何获取元素:使用javascript和CORS悬停背景
- 文本悬停效果加上背景更改
- 当我悬停按钮时,更改按钮的背景
- 文本的实时预览使链接在悬停时不会更改背景颜色
- 鼠标悬停时随机更改背景图像
- 悬停时缩放背景图像
- 如何在Javascript中悬停,将背景颜色更改为特定的类
- 在背景悬停时更改光标
- Facebook的哪些部分;s界面代码负责在悬停时更改徽标的背景颜色
- 悬停时的CSS背景
- 悬停时更改正文背景
- 更改元素父元素的背景颜色时停止在
上闪烁鼠标悬停?jQuery/JS. - 将鼠标悬停在子级上并更改父级背景颜色