折叠文本功能报错Uncaught TypeError,求问题排查方案
问题分析与解决方案
嘿,我一眼就发现问题所在了!咱们来一步步拆解:
错误原因
- 核心问题:你的折叠按钮被包裹在
<p>标签里,当你用this.nextElementSibling(这里的this指向点击的按钮)时,得到的是null——因为按钮在<p>内部,它没有直接相邻的兄弟元素。尝试访问null.style自然就会抛出Cannot read property 'style' of null这个错误。 - 次要小bug:代码里设置
maxHeight时用了content.scrollHeight,但你定义的变量名是levcontent,这会导致另一个content is not defined的错误。
修正后的代码
把获取内容元素的逻辑改成先找到按钮的父元素(也就是<p>),再取父元素的下一个兄弟节点,同时修正变量名的问题:
<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.parentElement.nextElementSibling; if (levcontent.style.maxHeight){ levcontent.style.maxHeight = null; } else { // 修正:变量名改为levcontent levcontent.style.maxHeight = levcontent.scrollHeight + "px"; } }); } </script>
这样修改后,点击按钮就能正常展开/折叠内容啦!
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

