簡體   English   中英

Javascript onclick 操作不適用於圖像或圖標

[英]Javascript onclick action not working on image or icon

我在下面找到了一個簡單的 javascript onclick function。

 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();
});

 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 部分,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM