我想在按下按钮时更改DIV的可见性。这段代码有什么问题
ID DATE
123 10/1/2014
456 6/1/2014
答案 0 :(得分:1)
您现有的代码应该有效。唯一的问题是您没有明确地设置addresses
属性(因为您的if语句正在检查):
visibility
如果它尚不存在,您可以通过添加它来解决此问题:
<!-- Since visibility wasn't there, your code couldn't detect it -->
<p id="myP" style='visibility: visible'>This is a p element.</p>
答案 1 :(得分:1)
原始HTML没有style="visibility: visible"
。因此which.style.visibility
会返回null
。因此,if(which.style.visibility)
失败。
添加显式样式,它应该有效。
function myFunction() {
var which = document.getElementById("myP");
if (which.style.visibility == "visible")
which.style.visibility = "hidden"
else
which.style.visibility = "visible"
}
<p id="myP" style="visibility: visible;">This is a p element.</p>
<button type="button" onclick="myFunction()">Hide content of p</button>
答案 2 :(得分:0)
<强>更新强> 我修复了代码,但它在第一次单击时仍会伪造显示属性。只有在您不想更改html标签时,此解决方案才有用。
使用style.display insead
function myFunction() {
var which= document.getElementById("myP");
if (which.style.display =="")
which.style.display = "none"
else
which.style.display = ""
}
答案 3 :(得分:0)
JQuery切换对此非常有用,请参阅小提琴:https://jsfiddle.net/uddhf4rw/2/
<p id="myP">This is a p element.</p>
<button type="button">Hide content of p</button>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#myP").toggle();
});
});
</script>
答案 4 :(得分:0)
corrct属性是
which.style.display
所以
function myFunction() {
var which= document.getElementById("myP");
if (which.style.display =="block" || which.style.display =="")
which.style.display = "none"
else
which.style.display = "block"
}
此fiddle为例
答案 5 :(得分:0)
首先,不要使用onclick属性。请改用addEventListener。
整个代码
var paragraph = document.getElementById("myP"),
currentState = window.getComputedStyle(paragraph, null).visibility;
document.querySelector("button").addEventListener("click", function() {
paragraph.style.visibility = paragraph.style.visibility === "hidden" || currentState === "hidden" ? "visible" : "hidden";
});
还可以考虑使用css显示而不是可见性。
答案 6 :(得分:0)
最初取消设置.style.visibility的值
function myFunction() {
var which= document.getElementById("myP");
if (!which.style.visibility || which.style.visibility=="visible")
which.style.visibility = "hidden"
else
which.style.visibility = "visible"
}
或
<p id="myP" style="visibility: visible;">This is a p element.</p>