以下代码(用于可折叠文本)会抛出以下错误:Uncaught TypeError:无法在HTMLButtonElement中读取null的属性“style”。发现错误的行是:if (levcontent.style.maxHeight){
可折叠文字的代码如下:
<style>
.collapsible {
height: 40px;
background-color: #444;
color: white;
cursor: pointer;
padding: 0px 10px 0px 10px;
margin: 2% 4% 2% 4%;
width: 93%;
border: none;
text-align: left;
outline: none;
font-size: 14px;
text-transform: capitalize;
}
.lev-active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.lev-active:after {
content: "\2212";
}
.levcontent {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
</style>
<p><button class="collapsible">Levering</button></p>
<div class="levcontent">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("lev-active");
var levcontent = this.nextElementSibling;
if (levcontent.style.maxHeight){
levcontent.style.maxHeight = null;
} else {
levcontent.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
有谁知道我做错了什么?
答案 0 :(得分:0)
该按钮是p
元素的唯一子元素。所以没有nextElementSibling
。
您可以删除p
元素,也可以将levcontent
设置为this.parentElement.nextElementSibling
。
此外,我发现了一个小错误:你在else块中使用了content.scrollHeight
而不是levcontent.scrollHeight
。
以下是修改后的工作代码:
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("lev-active");
var levcontent = this.parentElement.nextElementSibling;
if (levcontent.style.maxHeight){
levcontent.style.maxHeight = null;
} else {
levcontent.style.maxHeight = levcontent.scrollHeight + "px";
}
});
}
.collapsible {
height: 40px;
background-color: #444;
color: white;
cursor: pointer;
padding: 0px 10px 0px 10px;
margin: 2% 4% 2% 4%;
width: 93%;
border: none;
text-align: left;
outline: none;
font-size: 14px;
text-transform: capitalize;
}
.lev-active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.lev-active:after {
content: "\2212";
}
.levcontent {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<p><button class="collapsible">Levering</button></p>
<div class="levcontent">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>