在悬停/单击时设置背景内部div

时间:2012-06-23 10:01:18

标签: jquery html css

我有两个div:

<div class="outer">
    <div class="inner">Example</div>
</div>

我有一个jQuery函数:

$(function(){
    $('.outer').mouseout(function () {
        $('.outer).attr("style", "background-color: white");
    });

    $('.outer').mouseover(function () {
        $('.outer).attr("style", "background-color: red");
    });

    $('.inner').mouseout(function () {
        $('.inner).attr("style", "background-color: white");
    });

    $('.inner').mouseover(function () {
        $('.inner).attr("style", "background-color: red");
    });
});

当我将鼠标悬停在“外层”上时,外层背景为红色(好!)。当我盘旋内部时,内部和外部都是红色的......不好。

这个想法也适用于点击事件。当我向jQuery函数添加一些click-functions并单击内部div时,脚本会单击内部和外部div。

我只希望将一个div设置为红色,而不是当我将鼠标悬停在内部时。同样在将来,我想将此功能用于点击事件。

我认为这很简单,但我无法以某种方式弄明白:(

谁能帮帮我?

提前致谢

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找stopPropagation事件方法,它:

  

阻止事件冒泡DOM树,防止任何事件   家长处理人员被告知该事件。

所以解决方案如下:

$(".inner").hover(function(e) {
    e.stopPropagation();
    $(this).attr("style", "background-color: red");
}, function(e) {
    e.stopPropagation();
    $(this).attr("style", "background-color: white");
});

DEMO: http://jsfiddle.net/TZjpT/

答案 1 :(得分:0)

@Zoltan Toth: 我手工打字,所以我可能会忘记一些引用:)

对于所有其他人: 我关闭了stackoverflow,并且有一个网页,可以在后台找到问题的答案。我没有看到它......它解决了我的问题:

(element = a div)

 $(element).bind("click", function (event) {
     $(this).attr("style", "background-color: red");
     event.stopPropagation();
 });

抱歉给您带来不便

相关问题