我基本上是在尝试编写一个可以<div>
使用 JavaScript展开折叠的脚本。在使用前端部分时,我可以<div>
通过单击它来折叠和展开它,但是当涉及到 JavaScript 时,如果我尝试element.click()
甚至element.ariaExpanded = "true"
.
我附上了点击之前和之后的代码,<div>
突出显示代码中的差异。
我尝试了几件事,包括
var outerDiv = document.getElementsByClassName("section--section--BukKG");
outerDiv[0].ariaExpanded = "true";
outerDiv[0].children[0].ariaExpanded = "true";
outerDiv[0].click();
document.querySelectorAll('.section--section-chevron--tJ4mD')[0].classList.remove('udi-angle-down');
document.querySelectorAll('.section--section-chevron--tJ4mD')[0].classList.add('udi-angle-up');
由于您没有包含任何 HTML 标记,因此以下是原始文件的粗略复制品。您实际上是在尝试切换 DIV 元素的可见性,并使用 ARIA 标记指示该元素是或不是expanded
为此,您可以使用aria-expanded
CSS中的属性来控制父容器中子对象的可见性。通过将属性设置aria-expanded
为 true 或 false 将调用相关的 css 规则来显示/隐藏子项。
const bool=(v)=>v=='true' ? true : false;
const clickhandler=function(e){
this.setAttribute('aria-expanded', !bool(this.ariaExpanded) )
}
document.querySelectorAll('div.section--section--bukkg').forEach(div=>div.addEventListener('click',clickhandler) );
.section--section--bukkg{
transition:ease-in-out 250ms all;
border:1px solid red;
padding:1rem;
margin:1rem;
}
[aria-expanded="false"] .section--section--heading{
display:none;
}
[aria-expanded="true"] .section--section--heading{
display:block;
}
<div class='section--section--bukkg' data-purpose='section-panel' aria-expanded='false'>
<div class='section--section--heading' role='button' tabindex=0 data-purpose='section-heading'>
<div class='section-title' data-purpose='section-panel'>A title of some sort 1</div>
<span class='section-chevron'>Some content in a SPAN 1</span>
<div class='font-text-xs'>teeney weeney text 1</div>
</div>
</div>
<div class='section--section--bukkg' data-purpose='section-panel' aria-expanded='false'>
<div class='section--section--heading' role='button' tabindex=1 data-purpose='section-heading'>
<div class='section-title' data-purpose='section-panel'>A title of some sort 2</div>
<span class='section-chevron'>Some content in a SPAN 2</span>
<div class='font-text-xs'>teeney weeney text 2</div>
</div>
</div>
<div class='section--section--bukkg' data-purpose='section-panel' aria-expanded='false'>
<div class='section--section--heading' role='button' tabindex=2 data-purpose='section-heading'>
<div class='section-title' data-purpose='section-panel'>A title of some sort 3</div>
<span class='section-chevron'>Some content in a SPAN 3</span>
<div class='font-text-xs'>teeney weeney text 3</div>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句