首页 > 解决方案 > Javascript onclick 操作不适用于图像或图标

问题描述

我在下面找到了一个简单的 javascript onclick 函数。

  
    function dropdownFunction() {
      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');
          }
        }
      }
    }
<div class="dropdown">
      <button onclick="dropdownFunction()" class="dropbtn">Dropdown</button>
      <div id="myDropdown" class="dropdown-content">
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#contact">Contact</a>
      </div>
    </div>
    
 

当我尝试下面的 html 代码时,下拉内容不会弹出。

<div class="dropdown">
  <div class="dropbtn" onclick="dropdownFunction()">
    <%= image_tag "global-icon.png", alt: 'Language' %>
    <i class="icon-down-dir"></i>
  </div>
</div>

请告知我遗漏或错误的内容。

更新

我改为使用 jquery,它运行良好。

$(document).ready(function(){
    $('#droptoggle').click(function(event){
        event.stopPropagation();
         $("#myDropdown").slideToggle("1000");
    });
    $("#myDropdown").on("click", function (event) {
        event.stopPropagation();
    });
});
//close when click out of window
$(document).on("click", function () {
    $("#myDropdown").hide();
});

标签: javascripthtml

解决方案


function dropdownFunction() {
  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="dropdownFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

在这里添加了 CSS 部分,


推荐阅读