【问题标题】:Event bubbling issue in jqueryjquery中的事件冒泡问题
【发布时间】:2023-04-02 07:44:01
【问题描述】:

我正在使用如下所示的事件冒泡在鼠标悬停时调整 h3 标记文本的大小,并在鼠标未悬停在文本上时恢复到原始大小。但它不起作用。

$('body').hover(function (event) {
    if ($(event.target).is('h3')) {
        $(event.target).hover(function () {
            $(this).css("font-size", "40px");
        },
        function () {
            $(this).css("font-size", "40px");
        });
    }
}); 

我是新手。所以可能有一个愚蠢的错误。请指出。 在此先感谢各位。

【问题讨论】:

    标签: jquery event-bubbling


    【解决方案1】:

    您只需要将事件应用到h3 元素本身。试试这个:

    $("h3").hover(function() {
        $(this).css("font-size", "40px");
    },
    function() {
         $(this).css("font-size", "20px");
    });
    

    此外,最好使用 CSS 类来修改字体大小,因为它可以更好地分离关注点:

    $("h3").hover(function() {
        $(this).addClass("big-text");
    },
    function() {
         $(this).removeClass("big-text");
    });
    
    // CSS
    h3 { font-size: 12px; }
    .big-text { font-size: 40px; }
    

    更新

    由于h3 元素是动态加载的,您需要将on 与委托一起使用。试试这个:

    $("body").on("hover", "h3", function(e) {
        if (e.type == "mouseenter") {
           $(this).css("font-size", "40px");
        }
        else { // mouseleave
            $(this).css("font-size", "20px"); 
        }
    });
    

    我在这里使用body 作为主要选择器,但您应该使用最接近页面加载时可用的h3 元素的元素。

    【讨论】:

    • 对。但我的要求是不同的。我在页面上有一些按钮,它们使用 ajax 调用根据 click 加载其他文件。所以这些文件返回的文本也包含 h3 标记的文本。所以我也需要在这些上应用悬停。所以我正在使用上述程序。
    【解决方案2】:

    试试这个:

    $(document).on('mouseenter', 'h3', function(event) {
           $(this).css("font-size", "40px");
    })
    
    $(document).on('mouseleave', 'h3', function(event) {
           $(this).css("font-size", "20px");
    })
    

    或:

    $(document).on({
      mouseenter: function() {
           $(this).addClass('aClass')
      },
      mouseleave: function() {
           $(this).removeClass('aClass')
    }, 'h3')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2012-03-11
      • 1970-01-01
      相关资源
      最近更新 更多