我需要一些帮助。当我单击 THIS IS 1 和 THIS IS 2 时,输入框出现 我的问题是。我想单击 THIS IS 1 并将输入框带到 THIS IS 1 而不是单击 THIS IS 2 并且仍然将输入框带到 THIS IS 1。所以我想当我单击 THIS IS 1 时输入框出现在 THIS IS 1 下面当我单击 THIS 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>
最佳答案
如果你想使用相同的 showhide
div 显示在被点击的元素下,你可能需要在点击时使用 insertBefore
。
请参阅下面的代码段:
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
关于javascript - 在 html5 的支持下隐藏显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53071759/