有没有办法在选择选项中显示输入框,以便我可以在选项中添加一个值?
问题出现的原因是无法在选择框中放置输入框。但是下面提供了一种解决方法,通过使用data属性和隐藏的输入框来实现。以下是解决方法的详细说明:
1. 首先,在HTML中创建一个包含选择框和选项的容器:
Choose
2. 使用CSS样式对选择框和选项进行样式设置:
.select-container {} .select-container .select-field { display: inline-block; padding: 3px 20px; border-radius: 3px; border: 1px solid rgb(180, 180, 180); transition: 0.2s; cursor: pointer; } .select-container .select-field:hover { background-color: rgba(0, 0, 0, 0.1); } .select-container .select-options { position: absolute; z-index: 9999; overflow: hidden; background-color: white; display: none; border-radius: 3px; border: 1px solid rgb(180, 180, 180); transition: 0.1s; width: 60%; cursor: pointer; } .select-container .select-options div { padding: 4px 6px; border-bottom: 1px solid rgb(180, 180, 180); transition: 0.2s; } .select-container .select-options div:hover { background-color: rgba(0, 0, 0, 0.1); } .select-container .select-options div:last-of-type { border-bottom: none !important; } .select-container .select-options .clicked { background-color: rgba(60, 150, 210) !important; color: white; }
3. 使用JavaScript代码处理选择框的显示和选项的点击事件:
$(document).ready(function() { // 显示选项 $(".select-field").click(function() { $(".select-options").show(); }); // 处理选项点击 $(".select-option").click(function() { $(this).addClass("clicked"); $("#shp").val($(this).data("value")); $(".select-field").html($(this).data("area")); $(".select-option").not(this).each(function() { $(this).removeClass("clicked"); }); }); // 获取选择值 $(".getSelectValue").click(function() { alert($("#shp").val()); }); // 隐藏选项 $(window).click(function(e) { if ($(e.target).hasClass("select-option") || $(e.target).hasClass("select-input")) { } else { if (!$(e.target).hasClass("select-field")) { $(".select-options").css("display", "none"); } } }); });
这样,当用户点击选择框时,选项会显示出来。而当用户点击某个选项时,该选项的值会被赋给隐藏的输入框,并显示在选择框中。用户还可以通过点击按钮来获取选择的值。
这是一种可行的解决方法,可以通过使用上述代码和样式来实现在选择框中显示输入框并添加选项的值。