我需要一些帮助。当我单击“此为1”和“此为2”时,输入框出现 我的问题是。我想单击“此为1”并将输入框带至“此IS 1”,而不单击“此2”,仍将输入框带至“此IS 1”。因此,当我单击“此为1”时,我想输入的框位于“此IS 1”的下方。 IS 2输入框位于THIS IS 2下方
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<span onclick="MFunction()">THIS IS 1</span>
<p></p>
<span onclick="MFunction()">THIS IS 2</span>
<div id="showhide" style="display:none;">
<input type="text" required>
<br></br>
<button class="btn btn-md-2 btn-primary">submit</button>
</div>
<script>
function MFunction() {
var x = document.getElementById("showhide");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
如果要使用与单击时使用showhide
相同的insertBefore
div来显示单击元素下的内容。
请参见下面的摘录:
function MFunction(event) {
var x = document.getElementById("showhide");
if (x.style.display === "none") {
x.style.display = "block";
}
x.parentNode.insertBefore(x, event.target.nextSibling);
}
document.addEventListener('click', function(event){
if(event.target.className.includes("thisis")){
MFunction(event);
}
});
//document.getElementById("thisis1").addEventListener("click", MFunction);
//document.getElementById("thisis2").addEventListener("click", MFunction);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<span id="thisis1" class="thisis">THIS IS 1</span>
<p></p>
<span id="thisis2" class="thisis">THIS IS 2</span>
<p></p>
<span id="thisis3" class="donotshow">DO NOT SHOW ON THIS IS</span>
<div id="showhide" style="display:none;">
<input type="text" required>
<br><br>
<button class="btn btn-md-2 btn-primary">submit</button>
</div>
</body>
您也可以here对其进行测试
更新1:
我已经更新了答案,可以为多个元素添加单击事件。您可以here
对其进行测试