首页 > 解决方案 > 为什么 HTML 集合中的元素数量不等于 HTML 集合对象的长度?

问题描述

const profile = document.querySelector('#profile');

profile.addEventListener('mouseover', function() { 
   console.log('parent')
   const onHover = document.createElement('div');
   const hoverContent = document.createTextNode('my profile');
   onHover.setAttribute('id', 'miniProfile');
   onHover.append(hoverContent);
   onHover.style.height = '100px';
   onHover.style.width = '100px';
   onHover.style.backgroundColor = 'blue';
   onHover.style.position = 'absolute';
   onHover.style.top = '30px';
   this.append(onHover)
   setTimeout(()=> {
       onHover.style.top = '15px';
       onHover.style.transition = '1s'
       onHover.style.transitionTimingFunction = 'ease'
   }, 10)

    onHover.addEventListener('mouseover', function(e) { 
       // e.stopPropagation()
    })

})

profile.addEventListener('mouseout', function(e) { 
    
    if(e.relatedTarget.id.toLowerCase() !=        this.children[0].id.toLowerCase()) {
        console.log(this.children) 
        if(this.children.length != 0) { 
            for(let i = 0; i < this.children.length; i++) { 
                this.children[i].remove();
            }
        }
    }
})
#profile { 
    position: relative;
    display: inline-block;
    margin-left:100px;
    margin-top:50px;
    padding: 10px;
    background-color: red;
}
<div id="profile">My Profile</div>

当您将鼠标悬停在红色父框上,然后没有将鼠标悬停在蓝色子框上时,您只需将鼠标悬停在父蓝色框外,日志显示如下:

HTMLCollection [div#miniProfile, miniProfile: div#miniProfile]

但是当你打开它时,长度属性显示为 0。这是一个快照:

HTML 集合长度属性

为什么?

另外,如果你将鼠标悬停在子蓝色框上,你会生成很多新的子元素,然后当你悬停时,你会得到一个 HTML 集合,里面有很多元素,但长度几乎总是接近实际的一半元素。

这是一个快照:

HTML 集合

..再次,为什么?

标签: javascript

解决方案


推荐阅读