我有Bootstrap 4和一个输入组。我想点击我的img,然后显示一个选择菜单,点击一个选项后,这必须在输入字段中。我怎么能这样做?
<div class="input-group">
<input class="form-control" type="text">
<span class="input-group-addon">
<img src="./img/plus.png"alt="minus" class="align-middle">
</span>
</div>
答案 0 :(得分:2)
$("ul.dropdown-menu li a").on("click",function(){
$(this).closest(".input-group").find("input.form-control").val($(this).attr("data-Action"))
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://getbootstrap.com/docs/3.3/dist/js/bootstrap.min.js"></script>
<link href="https://getbootstrap.com/docs/3.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-sm-6" style="padding-top:10px;">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i style="padding-bottom:4px;" class="fa fa-plus"></i>
</button>
<ul class="dropdown-menu">
<li><a data-Action="1" href="#">Action 1</a></li>
<li><a data-Action="2" href="#">Action 2</a></li>
<li><a data-Action="3" href="#">Action 3</a></li>
</ul>
</div>
<input class="form-control">
</div>
</div>
答案 1 :(得分:0)
为了获得您正在寻找的结果,您需要做一些事情:
您可以通过在img
标记中添加event listener来显示选择菜单,这样当点击图片时,系统会显示选择菜单。
myImg.addEventListener('click', function() {
myMenu.style.display = "inline-block";
});
为了在输入框中显示所选选项,您需要另一个事件监听器:
myMenu.addEventListener('change', function(e) {
myInput.value = e.target.value;
});
将这两个事件监听器与一些CSS放在一起,<select>
菜单的HTML和一些变量声明为我们提供了这个工作代码:
$(document).ready(function() {
var myInput = document.getElementsByTagName('input')[0];
var myImg = document.getElementsByTagName('img')[0];
var myMenu = document.getElementById('selectMenu');
myImg.addEventListener('click', function() {
// when the img is clicked, show the select menu
myMenu.style.display = "inline-block";
});
myMenu.addEventListener('change', function(e) {
// when an option in the select menu is selected, show it in the input box
myInput.value = e.target.value;
});
});
#selectMenu {
display: none;
float: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet">
<div class="input-group">
<input class="form-control" type="text">
<span class="input-group-addon">
<img src="./img/plus.png"alt="minus" class="align-middle">
</span>
<br />
</div>
<select id="selectMenu">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
</select>
当然,使用Bootstrap或纯CSS,您可以根据需要设置菜单样式。