【问题标题】:Make effect only on hovered element in JQuery. - Same classes仅对 JQuery 中的悬停元素生效。 - 相同的课程
【发布时间】:2014-01-06 18:10:14
【问题描述】:

我有以下结构:

<div class="box a">
    <div class="box b">
        <div class="box c">

        </div>
    </div>
    <div class="box d">

    </div>
</div>

现在我要进行以下操作:如果我将鼠标悬停在最大的框 a 上,我想对其进行一些效果,例如不透明度。

但是,如果我将鼠标悬停在盒子 c(位于盒子 a 和 b 中)上,我只想在盒子 c 上制作不透明效果。

我尝试的是:

$('.box').mouseenter(function(e) {
    e.stopPropagation();
    $(this).css({'opacity': 0});
}).mouseleave(function(e) {
    e.stopPropagation();
    $(this).css({'opacity': 1});
});

但这不起作用。有谁知道解决办法吗?

我用 JS 和 CSS 都试过了,但两次都搞不定。在这里查看这两种解决方案会很有帮助。

【问题讨论】:

  • 不应该选择 .box.c 的效果吗?

标签: javascript jquery html css jquery-selectors


【解决方案1】:

您需要使用mouseover & mouseout

$('.box').mouseover(function (e) {
    e.stopPropagation();
    $(this).css({
        'opacity': .25
    });
}).mouseout(function (e) {
    e.stopPropagation();
    $(this).css({
        'opacity': 1
    });
});

演示:Fiddle

为什么,请查看 mouseenter 和 mouseleave 的 mdn 文档

【讨论】:

  • 你能告诉我为什么悬停不能像你的代码那样工作,但它们是一样的
  • $('.box').hover(function(e) { e.stopPropagation(); $(this).css({'opacity': 0}); },function(e ) { e.stopPropagation(); $(this).css({'opacity': 1}); });像这样
  • @Riturajratan 不一样...查看 mdn 文档... hover 注册 mouseenter 和 mouseleave 处理程序它们与 mouseover 和 mouseout 不同
【解决方案2】:

在你的脚本中试试这个

$('.c').mouseenter(function(e) {
e.stopPropagation();
$(this).css({'opacity': 0});
}).mouseleave(function(e) {
    e.stopPropagation();
    $(this).css({'opacity': 1});
});

【讨论】:

  • 如果我将鼠标悬停在 a 上,其他 2 个不会消失,这是错误的,无论如何谢谢
【解决方案3】:

这是因为你使用的类。请看下面的代码

<div class="box1">
    <div class="box">
        <div class="box">

        </div>
    </div>
    <div class="box d">
     </div>
</div>

以下将是 jquery 代码行

$('.box').mouseenter(function(e) {
$(this).css({'opacity': 0});
});
$('.box').mouseleave(function(e) {
    $(this).css({'opacity': 1});
});

和css

.box{
    width:100px;
    height:100px;
    background:red;
}

【讨论】:

    猜你喜欢
    • 2017-05-31
    • 1970-01-01
    • 2012-03-18
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多