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

When you hover the .container it changes the color of both. But I just want to change it of the container where the mouse is on

本文关键字:改变 只想 鼠标 颜色 container 悬停 当你      更新时间:2023-09-26

我准备了这个:

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来解决这个问题。

给外部元素一个公共类,然后:

.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', "");
});

.mouseenter函数中将$(".content")更改为$(this).find(".content"),它只会更改您悬停在上面的那个。您可以将其更改为$(".content", this),但根据评论中的epascarello,它不是那么有效。

你可以移动css background属性或者这样做:

moped = "";
$(".container").mouseenter(function () {
   $(this).children(".content").css('background', function () {
        moped = $(this).css('background-color');
        return "green";
    });
}).mouseleave(function () {
    $(this).children(".content").css('background', function () {
        return moped;
    });
});

我的建议是用脚本做并重构它,使用.hover()并分别命名mouseentermouseout函数。祝你好运,伙计。

相关文章: