我有简单的html:
<a href='#' id='target'>
<img src='https://sftextures.com/texture/6485/0/6487/metal-dots-very-dark-grey-black-solid-material-seamless-texture-256x256.jpg'/>
</a>
我想获取基本上应该复制图像的#target元素的高度:
let target = document.getElementById('target');
let height = target.getBoundingClientRect().height;
// result 18px, image size is 256px
为什么目标链接元素不会复制子代的高度?假设我的网站有数千个元素,但我无法识别孩子。在类似实际高度不匹配的情况下,如何获得正确的高度?
答案 0 :(得分:1)
让高度= target.offsetHeight。 请尝试一下。它正在工作
答案 1 :(得分:1)
如果元素更多,请尝试将<div>
设置为父元素。应该工作正常。
答案 2 :(得分:0)
显示为“内联阻止”
target.onclick = function () // just to take care of image loading delay
{
target.style.display = 'inline-block';
targetHeight.textContent = `parent height: ${target.getBoundingClientRect().height} px `;
image_Height.textContent = `img height: ${ImgInsideA.getBoundingClientRect().height} px `;
target.style.display = null;
console.log( target.getBoundingClientRect().height );
}
<a href='#' id='target'>
<img id="ImgInsideA"
src='https://sftextures.com/texture/6485/0/6487/metal-dots-very-dark-grey-black-solid-material-seamless-texture-256x256.jpg' />
</a>
<div id='targetHeight'> -- </div>
<div id='image_Height'> -- </div>