javascript - 当您悬停 .container 时,它会改变两者的颜色。但我只想更改鼠标所在的容器

标签 javascript jquery html css-selectors

我准备了这个:

http://jsfiddle.net/hXpWh/2/

当您将鼠标悬停在 .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/

相关文章:

html - 防止元素在 bootstrap 4 导航栏切换中折叠

html - 将文本置于 CSS 预加载器下方

javascript - 使用 jQuery 检测特定浏览器版本

javascript - 使用 jQuery 防止双击链接

javascript - 如何用css展开一个div

javascript - 当 event.target 返回子元素时,如何只获取点击事件的父元素?

javascript - react : How to know which component calls the function

javascript - 在javascript中,循环中的函数无法访问循环范围变量

javascript - 如何在 jquery nextUntil 中选择每隔一个元素?

javascript - jQuery - 检测点击浏览器后退按钮并提交表单