javascript - 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();
});
解决方案
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 部分,
推荐阅读
- java - Getter 方法使用
- android - 如何将位图图像横向设置为纵向
- certificate - SSLError:(“糟糕的握手:错误([('SSL例程','tls_process_server_certificate','证书验证失败')])”)))
- kubernetes - Kubernetes Autoscaler 如何始终保持一个节点处于空闲状态
- android - post方法中的自定义Gson请求和响应
- c - 用于在键盘上编程键的开关盒。到目前为止这似乎正确吗?
- bison - Bison 3.2 编译问题
- android - How to open the XMPP connection in react native throughout the entire app (using xmpp.js)?
- python - 如何在 for 循环中将多个旧字符串替换为新字符串?
- python - tensorflow 使用 GPU 与 CPU 计算损失