这是我的代码:
<img src="img/fastcall150.png" id="round" onclick="myFunction();" />
<img src="img/gesturecall150.png" id="round" onclick="myFunctio();" class="dropbtn" />
<div id="myDropdown" class="dropdown-content">
<a href="javascript:myFunc()"> Shake Gesture</a>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunctio() {
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');
}
}
}
}
</script>
这是 CSS:
.dropbtn {
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;*/
display: inline-block;*/
}
.dropdown-content {
display: none;
/* position: absolute;*/
text-align:center;
background-color: #fff400;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #dadada}
.show {display:block;}
这是我尝试过的方法,如果我在 button click 上提供此代码,一切正常。但是当我在 img click 上尝试同样的代码时,下拉菜单无法正确显示.
最佳答案
这是一个更新的片段。
第一个图像的
onclick
上有一个拼写错误myFunction();
。它应该是myFunctio();
。您需要将类
dropbtn
添加到第一张图片中或
将
if (!event.target.matches('.dropbtn')) {
更改为if (!event.target.matches('#round')) {
function myFunctio() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('#round')) {
document.getElementById("myDropdown").classList.toggle("show");
}
}
.dropbtn {
cursor: pointer;
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
position: relative;
*/ display: inline-block;
*/
}
.dropdown-content {
display: none;
/* position: absolute;*/
text-align: center;
background-color: #fff400;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #dadada
}
.show {
display: block;
}
<img src="img/fastcall150.png" id="round" onclick="myFunctio();" />
<img src="img/gesturecall150.png" id="round" onclick="myFunctio();" class="dropbtn" />
<div id="myDropdown" class="dropdown-content">
<a href="javascript:myFunc()"> Shake Gesture</a>
</div>
关于javascript - 如何在 imageclick 上做下拉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37811412/