繁体   English   中英

使按钮上的字体很棒的图标不可点击

[英]Make font-awesome icon on button not clickable

我有一个引导按钮,上面有一个很棒的字体图标。

<button type="button" class="btn pull-right rotate-picture-right" aria-label="Rotate" id="picture{{ picture.pk }}">
            <i class="fa fa-repeat"  id="testright" aria-hidden="true"></i>
          </button>

我的点击事件:

$(document).on('click', '.rotate-picture-right', function (e) {
  rotate_and_reload(e, "right");
});

功能:

function rotate_and_reload(e, direction){
    var picture_id = e.target.id.replace("picture", "")
    var url = "{% url "device-api-picture-rotate" device.pk 0 "placeholder" %}".replace("pictures/0", "pictures/"+picture_id).replace("placeholder", direction)
    $.ajax({
        url: url,
        type: 'PATCH',
        success: function() {
          var d = new Date();
          img = e.target.parentElement.parentElement.getElementsByTagName('img')[0];
          if (img.src.includes("?")){
            img.src = img.src.split("?")[0] + '?' + d.getTime();
          } else {
            img.src = img.src + '?' + d.getTime();
          }

        },
    });
}

在 Firefox 中,单击图标或按钮没有任何区别,按钮触发 on click 事件。 然而,在 Chrome 中,也可以单击图标,并且由于我使用了按钮数据的多个属性,如果我只获取图标信息,我的功能就会失败。 有没有办法“禁用”图标,只让它在那里并且漂亮但不能触发任何东西?

您可以使用 CSS 禁用图标上的指针事件。

 <button type="button" class="btn pull-right rotate-picture-right" aria-label="Rotate" id="picture{{ picture.pk }}"> <i class="fa fa-repeat" style="pointer-events:none" id="testright" aria-hidden="true"></i> </button>

但是,处理此问题的更好方法是确保event.target与单击事件处理程序中的event.currentTarget相同。 通过查看event.currentTarget属性,您始终可以获取按钮的引用而不是图标。 根据您使用的是 vanilla JS 还是像 jQuery 这样的框架,属性名称可能会有所不同。

样品:

 $('button').click(function(e) { console.log(e.currentTarget); // This will be the button even if you click the icon })

不同事件目标的方便参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM