نور*_*نور 6 html javascript search dom closest
注意:据我所知,该closest()方法在 DOM 树中搜索与指定 CSS 选择器匹配的最近元素。
当我点击margin两个li元素之间的空间..它返回null...但是如果我替换margin-bottom: 15px;为padding-bottom...一切都好...
CSS代码
.amenities-filters-inner ul li{
margin-bottom: 15px;
}
Run Code Online (Sandbox Code Playgroud)
如果我单击红色标记区域,则图像..找不到兄弟li元素..
示例代码
.amenities-filters-inner ul li{
margin-bottom: 15px;
}
Run Code Online (Sandbox Code Playgroud)
document.querySelectorAll(".amenities-filters-inner ").forEach(function(item){
item.addEventListener("click",function(e){
e.preventDefault();
let element = null;
element = e.target.closest(".amenity_id");
// element = e.target.querySelector(".amenity_id");
element = element.children[0].children[1];
element.checked == true ? element.checked = false : element.checked =true;
let dataId = + element.getAttribute('data-id');
console.log(element)
console.log(dataId)
})
})Run Code Online (Sandbox Code Playgroud)
.amenities-filters-inner{
border: 2px dashed royalblue;
max-width: 300px;
padding: 1rem;
}
ul{
list-style: none;
width: 100%;
margin: 0;
padding: 0;
}
li{
border: 2px solid rgb(133, 129, 129);
padding: 3px;
}
.amenities-filters-inner:last-child{
margin-bottom: 0;
}
.amenities-filters-inner ul li{
margin-bottom: 20px;
}
.amenities-filters-inner ul li:last-child{
margin-bottom: 0;
}
.check {
display: flex;
align-items: center;
justify-content: space-between;
position: relative;
padding-left: 31px;
margin-bottom: 0;
padding-right: 0;
cursor: pointer;
font-size: 14px;
color: #646464;
}
.check strong{
color: #969696;
font-size: 14px;
font-weight: 400;
}
.check input {
position: absolute;
opacity: 0;
cursor: pointer;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 17px;
width: 17px;
background-color: #fff ;
border-color: #646464;
border-style:solid;
border-width:1px;
border-radius: 2px;
}
.check input:checked ~ .checkmark {
background-color: #fff;
border-color: #007FEB;
}
.checkmark:after {
content: "";
position: absolute;
display: none;
}
.check input:checked ~ .checkmark:after {
display: block;
}
.check .checkmark:after {
left: 5px;
top: 1px;
width: 5px;
height: 10px;
border: solid ;
border-color:#007FEB;
border-width: 0 2px 2px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}Run Code Online (Sandbox Code Playgroud)
.closest()方法只遍历parents,不遍历children。
该区域位于容器中.amenities-filters-inner而不是列表元素内,因此它找不到.amenities-id.
更改容器的背景颜色以进行调试。
.amenities-filters-inner{
background: red;
}
Run Code Online (Sandbox Code Playgroud)
如果您不希望列表项之间有间隙,请不要使用边距。使用padding-topandpadding-bottom代替。
该
closest()方法遍历 Element 及其父级(指向文档根),直到找到与提供的选择器字符串匹配的节点。将返回自身或匹配的祖先。如果不存在这样的元素,则返回null。
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
| 归档时间: |
|
| 查看次数: |
10664 次 |
| 最近记录: |