【问题标题】:Icon interfering with button click event图标干扰按钮单击事件
【发布时间】:2019-05-15 17:28:06
【问题描述】:

我有一个包含图标的按钮。我相信该图标干扰了我的点击事件。我只能单击图标边距以激活 onclick 事件,但单击图标时没有任何反应。我用一些文本替换了图标,并且按钮 onclick 工作得很好。我尝试过 z-index 将图标放在按钮后面,但无济于事。有人可以解释为什么该图标会阻止点击发生以及我该如何解决?

html:

<div class="navMenu">
     <button onclick="navClick()" class="navMenu-button"><i class="fas fa-bars"></i></button>
     <div id="navList" class="navMenu-content">
           <a href="index.htm" class="navMenu-link">Home</a>
           <a href="about.htm" class="navMenu-link">About</a>
           <a href="resume.htm" class="navMenu-link">Resume</a>
     </div>

萨斯:

    .navMenu{
    position: relative;
    display: inline-block;
    margin-top:5px;
    margin-left:5px;
    &-button {
      background-color: #615b5b;
      border-radius:50%;
      color: white;
      padding: 7px;
      opacity:0.7;
      border:none;
      font-size: 14px;
      cursor: pointer;
    }
    &-button:hover, &-button:focus {
      background-color: #615b5b;
    }
    &-content {
      display: none;
      position: absolute;
      background-color: #f1f1f1;
      min-width: 200px;
      box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
      z-index: 1;
    }
    &-content .navMenu-link{
      color: $body-text-color;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
    }
    &-content .navMenu-link:hover {
        background-color: #ddd;
    }
    &-show {
        display:block;
    }
}

js:

function navClick() {
document.getElementById("navList").classList.toggle("navMenu-show");
}
window.onclick = function(event) {
if (!event.target.matches('.navMenu-button')) {
     var dropdowns = document.getElementsByClassName("navMenu-content");
     var i;
     for (i = 0; i < dropdowns.length; i++) {
       var show = dropdowns[i];
       if (show.classList.contains('navMenu-show')) {
          show.classList.remove('navMenu-show'); 
        }
     }
   }
}

【问题讨论】:

    标签: javascript html css sass


    【解决方案1】:

    发生这种情况是因为您正在设置一个事件来验证单击的元素是否包含特定的类,并且实际上当它单击图标时,它不会匹配,因为图标不包含您可以解决的类,询问是否父级也包含类....

    window.onclick = function(event) {
    
       if (event.target.matches('.navMenu-button') || 
          event.target.parentNode.matches('.navMenu-button')
       ) {
        console.log("it matches..."); 
       }
    }
    .icon {
    background:red;
    }
    <button class="navMenu-button">this is the button
      <div class="icon">this is the icon</div>
    </button>

    另一方面,您可以使用“onclick”方法引用点击事件,在这种情况下它会自动解决它..

    var button = document.querySelectorAll('.navMenu-button')[0];
    button.onclick = function() {
      console.log("button clicked");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多