【发布时间】:2022-08-24 23:02:13
【问题描述】:
我在页面上有一个简单的下拉菜单。单击它会触发一个 javascript 函数。代码在这里:
HTML
<div class=\"dropdown\">
<button onclick=\"myBrandDropdown()\" class=\"dropbtn\">
Brand name ▾
</button>
<div id=\"myDropdown\" class=\"dropdown-content\">
<a href=\"#\">Link 1</a>
<a href=\"#\">Link 2</a>
<a href=\"#\">Link 3</a>
</div>
</div>
CSS
.dropbtn {
background-color: transparent;
padding: 10px;
font-size: 1.4rem;
border: none;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
cursor: pointer;
}
/* Dropdown button on hover*/
.dropbtn:hover {
border: none;
text-decoration: none;
}
/* Dropdown button on focus */
.dropbtn:focus {
background-color: #293241;
border: none;
text-decoration: none;
color: #fff;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #293241;
min-width: 160px;
color: #fff;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border-top-right-radius: 4px;
}
/* Links inside the dropdown */
.dropdown-content a {
color: #fff;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {
background-color: #ddd;
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {
display: block;
}
JS
function myBrandDropdown() {
document.getElementById(\"myDropdown\").classList.toggle(\"show\");
}
// Close the dropdown menu 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\");
}
}
}
};
到目前为止,一切正常。
但是,我想为按钮内的文本添加一些下划线样式,但比简单的下划线文本装饰具有更多的控制权。所以我将文本包裹在一个跨度中,并给出我想要的样式。看这里:
更新的 HTML
<div class=\"dropdown\">
<button onclick=\"myBrandDropdown()\" class=\"dropbtn\">
<span class=\"dropbtnunderline\">Brand name</span>
▾
</button>
<div id=\"myDropdown\" class=\"dropdown-content\">
<a href=\"#\">Link 1</a>
<a href=\"#\">Link 2</a>
<a href=\"#\">Link 3</a>
</div>
</div>
新的 CSS
.dropbtnunderline {
display: inline-block;
border-bottom: 3px solid #e63946;
padding-bottom: 2px;
padding-top: 5px;
}
由于添加了跨度,按钮不再正确触发。它看起来和我想要的完全一样,点击文本周围的空间会正确触发,但点击文本本身什么也不做。
这是什么原因造成的,我可以轻松解决吗?
标签: javascript css