首页 > 解决方案 > event.preventDefault() 在任何浏览器中都不起作用

问题描述

我有 WP Bakery 的 Post Masonry Grid 创建的以下标签:

<a href="https://www.domain.nl/some-page/" class="vc_gitem-link vc_general vc_btn3 vc_btn3-size-md vc_btn3-shape-rounded vc_btn3-style-modern vc_btn3-o-empty vc_btn3-color-grey" title="some value in the title"><span class="vc_btn3-placeholder">&nbsp;</span></a>

当此链接悬停时,网格项目上会出现一个彩色叠加层。在移动设备上,这种效果是不可见的。我想要的是当用户点击这个链接时,覆盖出现在链接激活之前。我已经使用以下 jQuery 代码进行了尝试:

$('.project-item .vc_btn3-container a').click(function(event) {
        // Remember the link href
        var href = this.href;

        // Don't follow the link
        event.preventDefault();

        // Do the async thing
        overlayActive(function() {
            if($(window).width() <= 480) {
                console.log('it works');
                $(this).parent().parent().find('project-overlay-color').css('transform', 'scale(1,1)');
                // go to the link
                window.location = href;
            }
        });
    });

这在任何浏览器中都不起作用。另外,我在控制台日志中找不到“它有效”。我试图将它放在 click 函数中,但控制台日志仍然为空。

当我在 Chrome 中使用检查器并将其设置为移动设备(如 iphone X)时,当我单击链接时,覆盖出现在链接被激活之前。但是,在我自己的移动设备上,叠加层不会出现。

如何在链接激活并导航到页面之前显示叠加层?

标签: javascripthtmlcss

解决方案


您的选择器不好vc_btn3-container,不存在。尝试这个:

JS

$('.vc_gitem-link').click(function(event) {
  // Remember the link href
  var href = this.href;

  // Don't follow the link
  event.preventDefault();

  // Do the async thing
  overlayActive(function() {
    if($(window).width() <= 480) {
      console.log('it works');
      $(this).parent().parent().find('project-overlay-color').css('transform', 'scale(1,1)');
      // go to the link
      window.location = href;
    }
  });
});

演示


推荐阅读