本文介绍了如何使用.querySelectorAll选择器定位.style属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已通过 .querySelectorAll
选择了特定类别:
var hit3 = document.querySelectorAll(。lattern.hit-3 .circle);
我现在试图定位和调整 .style.visibility
属性,通过执行以下操作:
hit3.style.visibility =visible;
但这会导致错误:
未捕获类型错误:无法设置未定义的属性可见性
如何使用上述 .querySelectorAll
选择器来定位特定的 .style
?
解决方案
querySelectorAll
返回没有 style
属性。
但我认为你需要的是略有不同,我想要显示的点击元素的圆形,然后
.lattern {position:relative; width:100px; height:50px; background-color:red; margin:0 0 10px 0; cursor:pointer;}。circle {position:relative; top:20px; left:20px; border-radius:50%50%; width:16px; height:16px; background-color:green; visibility:hidden;}。circle.default,.circle.visible {visibility:visible;}
< div class =lattern hit-1> < div class =circle>< / div>< / div>< div class =lattern hit-2> < div class =circle default>< / div>< / div>< div class =lattern hit-3> < div class =circle>< / div>点击我< / div>
I have selected a specific class via .querySelectorAll
:
var hit3 = document.querySelectorAll(".lattern.hit-3 .circle");
I am now trying to target and adjust a .style.visibility
attribut on this element, by doing the following:
hit3.style.visibility = "visible";
This however results in an error:
Uncaught TypeError: Cannot set property 'visibility' of undefined
How do I target a specific .style
with the above .querySelectorAll
selector?
解决方案
querySelectorAll
returns an array like structure(NodeList) which does not have the style
attribute.
But I think what you need is slightly different, I assume want to display the circle for the clicked element then
var latternElement = document.querySelectorAll('.lattern');
function toggleElement(el) {
el.querySelector('.circle').classList.add('visible'); //also minor tweaks, use css rules
}
for (var i = 0; i < latternElement.length; i++) {
latternElement[i].addEventListener('click', function(event) {
if (this.classList.contains("hit-3")) { //minor tweaks - only supported in modern browsers
toggleElement(this);
}
});
}
.lattern {
position: relative;
width: 100px;
height: 50px;
background-color: red;
margin: 0 0 10px 0;
cursor: pointer;
}
.circle {
position: relative;
top: 20px;
left: 20px;
border-radius: 50% 50%;
width: 16px;
height: 16px;
background-color: green;
visibility: hidden;
}
.circle.default,
.circle.visible {
visibility: visible;
}
<div class="lattern hit-1">
<div class="circle"></div>
</div>
<div class="lattern hit-2">
<div class="circle default"></div>
</div>
<div class="lattern hit-3">
<div class="circle"></div>
click me
</div>
这篇关于如何使用.querySelectorAll选择器定位.style属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!