我实现了一个可折叠按钮,它在WP中运行良好,但如果我将其插入ul
列出它不工作,即按钮未打开。
然后,我尝试在JSFIDLE中运行代码,它确实起到了作用。
WP代码和JSFIDLE代码之间的唯一区别在于javascript
WP上的var content
定义为this.parentElement.nextElementSibling;
在jsfiddle上var content
定义为this.nextElementSibling;
这是因为
通过移除parentElement
在WP上,按钮将通过添加parentElement
在JSFIDLE上,按钮将断开仅供参考,WP上的javascript加载在页脚中。
有可能解决这个问题吗?这是jsfiddle demo.
下面您可以看到JSFIDLE vs WP
来自CHROME INSPECT TOOL的HTML
<div class="entry-content">
<p>Does <button class="col">this</button> work?</p>
<div class="con space" style="">
<p>Yes!</p>
<p></p></div>
<hr>
<ul>
<li>Does <button class="col">this</button> work?
<div class="con space">
<p>Only in jsfiddle, not in WP!</p>
</div>
</li>
<li style="">another line</li>
</ul>
</div>
来自WP CLASSIC EDITOR的HTML
Does <button class=col>this</button> work?
<div class="con space"><p>Yes!<p/></div>
<hr>
<ul>
<li>Does <button class=col>this</button> work?
<div class="con space"><p>Only in jsfiddle, not in WP!</p></div></li>
<li>another line</li>
</ul>
The
space
类仅包含
margin-bottom: 1.5em;
最合适的回答,由SO网友:sound wave 整理而成
Steven提供的解决方案
<script type="text/javascript">
( function() {
coll = document.getElementsByClassName("col");
conn = document.getElementsByClassName("con");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].setAttribute(\'data-id\', \'con\' + i);
conn[i].setAttribute(\'id\', \'con\' + i);
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = document.getElementById(this.getAttribute(\'data-id\'));
if (content.style.maxHeight) {
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
} )();
</script>