我正在使用下面給出的下拉菜單代碼。當正常使用菜單的圖像時,代碼工作正常。但是,我希望相對放置下拉菜單,即使瀏覽器窗口調整大小(響應式網頁設計)時也可以正確瀏覽菜單圖標。所以我將圖像元素包裝在div元素中,以便我可以使用絕對和相對屬性來定位它們。但是,一旦我將圖像封裝在div元素中,javascript就會停止工作。下拉菜單的顯示保持不變。下拉菜單不顯示
HTML
Javascript
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").style="display:block";
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.menu')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.style="display:block") {
openDropdown.style="display:none";
}
}
}
}
</script>
Inside the body
<div class="header">
<h1 class="title">Hello </h1>
<div class="dragon-logo">
<img id="dragon-img" src="pathtomascot.svg" />
</div>
<div class="menu">
<img onclick="myFunction()" src="pathtomenuicon.svg">
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</div>
CSS
/*For the menu icon*/
.menu {
display: block;
position: absolute;
z-index: 0;
height:55px; /* 150/640 */
width:55px;/*150/1536*/
top: 2.5%;
right: 10.0208333333%;
float: right;
cursor: pointer;
}
/* Dropdown button on hover & focus */
.menu:hover, .menu:focus {
background-color: #3e8e41;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
margin-top:
margin-left: 69%;
background-color: #f9f9f9;
min-width: 11%;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 2;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}
Thanks repzero! – MohanVS