逻辑是这样的,当您单击列表项时,例如“Ufa”,此文本会出现在当前的位置,以及列表中的当前位置。
window.onclick = function(event) {
if (!event.target.matches('.dropdown-toggle')) {
let dropdownMenu = document.getElementsByClassName('dropdown-menu');
for (let i = 0; i < dropdownMenu.length; i++) {
let openDropdown = dropdownMenu[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
};
const dropdownToggle = document.querySelectorAll('.dropdown-toggle');
dropdownToggle.forEach(function(item) {
item.onclick = function() {
this.nextElementSibling.classList.toggle('show')
};
});
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-toggle {background: orange;}
.dropdown-menu {
display: none;
position: absolute;
background-color: #f1f1f1;
overflow: auto;
z-index: 1;
}
.show {
display: block;
}
<div class="dropdown">
<div class="dropdown-toggle">Москва</div>
<ul class="dropdown-menu">
<li class="dropdown-item">Санкт-Петербург</li>
<li class="dropdown-item">Уфа</li>
</ul>
</div>
像这样试试
另外的选择