【问题标题】:how to make font-awesome icon in button clickable?如何使按钮中的字体真棒图标可点击?
【发布时间】:2021-04-19 02:07:05
【问题描述】:

我在按钮中有一个图标。当我单击按钮时(实际上是按钮区域的其余部分,图标除外),按钮将在其下方显示一个下拉列表。但是,当我单击按钮中的向下箭头图标时,下拉列表不会显示。我需要确保按钮和图标都是可点击的。我该怎么做?

这里是sn-p的代码:

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}
    
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}
#myDropdown {
  display: none;
}
#myDropdown.show {
  display: block;
}
<div class="dropdown">
    <button onclick="myFunction()" class="btn dropbtn btn-primary">
        More <i style='font-size:16px' title='More' class='fas'>&#xf0d7;</i>
    </button>

    <div id="myDropdown" class="dropdown-content" style="line-height:15px;">                
        <a href="#" target="_blank">Duplicate New</a>
        <a href="#" target="_blank">Download PDF</a>
        <a href="#" target="_blank">Print PDF</a>        
        <a href="#" class="delete" data-id="{{ $dataTypeContent->getKey() }}" id="delete-{{ $dataTypeContent->getKey() }}">Delete</a>        
    </div>
</div>

【问题讨论】:

  • 在移动设备上运行良好。

标签: html jquery css bootstrap-4 font-awesome


【解决方案1】:

window.onclick 函数也应在您单击 &lt;button&gt;&lt;i&gt; 时触发,但由于当您单击 &lt;i&gt;event.target 不是 dropbtn 它很可能会通过if (!event.target.matches('.dropbtn')) 检查并关闭下拉菜单,就像单击屏幕上的其他位置一样。

我会尝试if (!event.target.matches('.dropbtn') &amp;&amp; !event.target.matches('.fas')) 看看是否可以解决问题。如果是这样,我会向&lt;i&gt; 添加一个更具体的类,例如dropdown-toggle 并检查它是否匹配,否则如果您单击屏幕上的任何其他字体真棒图标,它不会关闭下拉列表。

更新 - 看起来是这样,这里是 JSFiddle https://jsfiddle.net/p1kw746q/

【讨论】:

  • 或者您可以将其键入为!event.target.matches('.dropbtn, .dropbtn *') 以简化,以便它会检查是否是dropbtn 触发了事件,或者dropbtn 中的所有内容是否有任何其他元素
猜你喜欢
  • 2014-03-06
  • 1970-01-01
  • 2020-11-30
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 2018-12-12
  • 2015-12-30
  • 2014-06-09
相关资源
最近更新 更多