我遇到以下问题:我必须单击两次按钮才能使脚本起作用,但我不知道为什么。我试图通过搜索阅读一些帖子,但没有一个解决了我的问题。
感谢您的帮助。
#div1{width: 400px; background-color: beige; transition: 1s}
.div2{background-color: aquamarine}
.div2 button{float: right; width: 50px;cursor: pointer; outline: none}
.div2 p{height: 0px;overflow: hidden;transition: 1s}
.div3 img{padding: 5%}
<div id="div1">
<div class="div2">
<h3>prova 1<button id="buttonst" onClick="showtext()">+</button></h3>
<p id="ptext">lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, </p>
<script>
function showtext(){
var but = document.getElementById("buttonst");
var p = document.getElementById("ptext");
var div = document.getElementById("div1");
if (p.style.height === "0px"){
but.innerHTML = "v";
p.style.height = "200px";
div.style.backgroundColor = "aquamarine";
} else {
but.innerHTML = "+";
p.style.height = "0px";
div.style.backgroundColor = "beige";
}
}
</script>
</div>
<div class="div3">
<img src="imagefile" alt="" width="90%">
</div>
</div>
答案 0 :(得分:1)
第一次进入函数的else块。我解决了在
标记上添加style =“ height:0”的问题。
<div id="div1">
<div class="div2">
<h3>prova 1<button id="buttonst" onClick="showtext()">+</button></h3>
<p id="ptext" style="height:0">lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum,
lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, lorem ipsum, </p>
<script>
function showtext(){
var but = document.getElementById("buttonst");
var p = document.getElementById("ptext");
var div = document.getElementById("div1");
if (p.style.height === "0px"){
but.innerHTML = "v";
p.style.height = "200px";
div.style.backgroundColor = "aquamarine";
} else {
but.innerHTML = "+";
p.style.height = "0px";
div.style.backgroundColor = "beige";
}
}
</script>
</div>
<div class="div3">
<img src="imagefile" alt="" width="90%">
</div>
</div>
答案 1 :(得分:0)
您的代码检查ptext元素的style属性,该属性仅涉及内联样式。由于高度是由CSS类而不是内联样式应用的。
根据Kurohige的建议,您可以从一开始就将高度作为内联样式添加,或者,如果您喜欢当前使用CSS,则可以在this question中提出解决方案。 / p>