html点击输入框弹出一个弹窗,弹窗内容是一个单选框,然后将单选框最后选定内容返回给输入框
时间: 2024-05-09 11:17:05 浏览: 204
input框只能输入数字和一个小数点
3星 · 编辑精心推荐
可以通过添加 JavaScript 代码来实现这个功能。首先,在 HTML 中添加一个输入框和一个按钮:
```
<input type="text" id="myInput" onclick="showPopup()" />
<button onclick="hidePopup()">Close Popup</button>
```
然后,定义 `showPopup()` 函数,在函数中创建一个弹窗,将单选框添加到弹窗中,并在用户选定内容后将其返回给输入框:
```
function showPopup() {
// create popup div
var popup = document.createElement("div");
popup.id = "popup";
popup.style.position = "absolute";
popup.style.top = "50%";
popup.style.left = "50%";
popup.style.transform = "translate(-50%, -50%)";
popup.style.backgroundColor = "#fff";
popup.style.padding = "20px";
popup.style.border = "1px solid #ccc";
// create radio buttons
var radio1 = document.createElement("input");
radio1.type = "radio";
radio1.name = "popupRadio";
radio1.value = "Option 1";
var label1 = document.createElement("label");
label1.innerHTML = "Option 1";
var radio2 = document.createElement("input");
radio2.type = "radio";
radio2.name = "popupRadio";
radio2.value = "Option 2";
var label2 = document.createElement("label");
label2.innerHTML = "Option 2";
// add radio buttons to popup
popup.appendChild(radio1);
popup.appendChild(label1);
popup.appendChild(document.createElement("br"));
popup.appendChild(radio2);
popup.appendChild(label2);
// add popup to page
document.body.appendChild(popup);
}
function hidePopup() {
var popup = document.getElementById("popup");
var radios = document.getElementsByName("popupRadio");
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById("myInput").value = radios[i].value;
break;
}
}
document.body.removeChild(popup);
}
```
当用户点击输入框时,会弹出一个弹窗,在弹窗中选择选项后,点击关闭按钮,弹窗消失并将选择的选项值返回给输入框。
阅读全文