我准备了这个:
当您将鼠标悬停在 .container 上时,它会改变两者的颜色。但我只想更改鼠标所在的容器。
这是js代码:
moped = "";
$(".container").mouseenter(function () {
$(".content").css('background', function () {
moped = $(this).css('background');
return "green";
});}).mouseleave(function () {
$(".content").css('background', function () {
return moped;
});
});
html:
<div class="container">
<div class="content"></div>
<div class="caption">
<p>This is the caption of .container</p>
</div>
</div>
<div class="container2">
<div class="content"></div>
<div class="caption">
<p>This is the caption of .container2</p>
</div>
</div>
CSS:
.container {
position: absolute;
top: 0;
left: 0;
display: block;
z-index: 800;
width: 250px;
height: 250px;
padding: 0;
margin: 0;
}
.container2 {
position: absolute;
top: 0;
left: 255px;
display: block;
z-index: 800;
width: 250px;
height: 250px;
padding: 0;
margin: 0;
}
.content {
display: block;
background: red;
position: absolute;
z-index: 900;
top: 0;
left: 0;
width: 250px;
height: 250px;
}
.caption {
display: block;
background: none;
position: absolute;
z-index: 1000;
top: 0;
left: 0;
width: 250px;
height: 250px;
}
.caption p {
position: relative;
bottom: 10px;
left: 10px;
}
最佳答案
其他答案显示了 jQuery 代码中的错误,但另一个解决方法是为此仅使用 CSS。
给外部元素一个公共(public)类,然后:
.cont {
background:red;
}
.cont:hover .content {
background: green;
}
演示: http://jsfiddle.net/hXpWh/4/
但是对于jQuery代码,不仅需要找到嵌套的.content
,而且不需要变量。只需在 mouseleave
中将背景设置为 ""
。
$(".container").mouseenter(function () {
$(this).find(".content").css('background', "green");
}).mouseleave(function () {
$(this).find(".content").css('background', "");
});
关于javascript - 当您悬停 .container 时,它会改变两者的颜色。但我只想更改鼠标所在的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860758/