我有一个自定义的下拉菜单,我想将下拉列表中的选定值添加到表单组。
下拉菜单如下所示:
.dropbtn {
background-color: #1a2835;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
border-style: solid;
border-color: #ffffff;
border-width: thin;
width: 150px;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #1a2835;
}
我这样用:
<div class="panel panel-default">
<div class="panel-heading">Chose option</div>
<div class="panel-body">
<div class="dropdown" style="margin-bottom: 30px;">
<button class="dropbtn">Día</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</div>
</div>
我的问题是,如果您点击表单组,如何使用选择器,如何添加所选内容。
答案 0 :(得分:1)
这样的动态内容需要JavaScript。您将一个click事件添加到下拉列表元素,并将处理程序传递给基本上附加到表单的事件。像这样(我没有包含你的CSS,所以你的下拉列表看起来不像下拉列表):
const dropdownElems = Array.from(document.querySelectorAll('.dropdown-content a'));
const formElem = document.getElementById('abc');
const dropdownElementClicked = function dropdownElementClicked(ev) {
const elemToAdd = document.createElement('a');
elemToAdd.innerHTML = ev.target.innerHTML;
formElem.appendChild(
elemToAdd
);
};
dropdownElems.forEach( elem => elem.addEventListener('click', dropdownElementClicked) );
&#13;
<div class="panel panel-default">
<div class="panel-heading">Chose option</div>
<div class="panel-body">
<div class="dropdown" style="margin-bottom: 30px;">
<button class="dropbtn">Día</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</div>
</div>
<form id='abc'>
</form>
&#13;