在 mousenter(悬停)上,显示和隐藏(切换)子元素

On mousenter (hover), show and hide (toggle) a child element

本文关键字:切换 隐藏 元素 mousenter 悬停 显示      更新时间:2023-09-26

有多个div 具有一个公共类。我想使用它的类在悬停时隐藏/显示每个div。我更喜欢使用mouseenter/mouseleave。但问题是$target = this.id;似乎不起作用。

如何使用类显示/隐藏 DIV?

$(".zz")
            .on( 'mouseenter', function() {
                $target = this.id;
                if( $target.is(':visible') ) return;
                    $target.hide();
            })
            .on( 'mouseleave', function() {
                    $target = this.id
                    if( !$target.is(':visible') ) return;
                        $target.show();
            });

编辑:js小提琴

与其将所有on()方法链接在一起,更好的方法是将所有事件合并到一个方法中:

$(document).on({
    mouseenter: function() {
        $(this).find('div[id^="im"]').hide();
    },
    mouseleave: function() {
        $(this).find('div[id^="im"]').show();
    },
    click: function() {
        // do something else
    }
}, ".zz");

希望这有帮助。

请参阅此演示。

尝试使用 jQuery(this)

或 $(this) 来使用您要输入/离开的元素,并希望从中添加/删除隐藏类。

$(".zz")
   .on( 'mouseenter', function() {
      if( $(this).is(':visible') ) return;
      $(this).show();
   })
   .on( 'mouseleave', function() {
      if( !$(this).is(':visible') ) return;
      $(this).hide();
   });

https://jsfiddle.net/n3syhn67/2/

更新了您的代码。希望对:)有所帮助

$(".zz")
        .on( 'mouseenter', function(event) {
            $target = $(event.target);
            //$target = this.id;
            if( $target.is(':visible') ) return;
                $target.show();
        })
        .on( 'mouseleave', function(event) {
                $target = $(event.target);
                //$target = this.id
                if( !$target.is(':visible') ) return;
                    $target.hide();
        });

使用

target = $(this);

this将引用您想要的 HTMLDiv。您必须将其转换为jQuery对象才能使用jQuery函数.is(':visible').hide()

       .on( 'mouseenter', function() {
            $target = $(this).find("img");
            if( $target.is(':visible') ) return;
                $target.show();
        })
        .on( 'mouseleave', function() {
                $target = $(this).find("img");
                if( !$target.is(':visible') ) return;
                    $target.hide();
        });

我已将目标更改为img元素,因为如果您隐藏整个潜水,您将永远无法再次将其带回mouseenter

编辑:

作为替代解决方案,您可以使用不透明度而不是隐藏。

    .on( 'mouseenter', function() {
            $target = $(this);
            $target.css({opacity:1});
     })
    .on( 'mouseleave', function() {
            $target = $(this);
            $target.css({opacity:0});
     })

例 仅隐藏图像例 隐藏不透明度的div