繁体   English   中英

居中图像左上角的叠加元素

[英]Overlay element at top-left corner of centered image

我有一个使用 flexbox 当前位于屏幕中心的图像:

.center-flex {
    display: flex;
    justify-content: center;
}

<div class="center-flex">
    <img id="revealImage">
</div>

我正在尝试动态创建一个需要放置在左上角的div 我尝试了以下方法将计算机left在图像上,但它无法正常工作,因为它返回auto

const revealImage = document.getElementById('revealImage');

const left = window.getComputedStyle(revealImage,null).getPropertyValue('left');

let square = document.createElement('div');
square.style.height = '100px';
square.style.width = '100px';
square.style.zIndex = '2';
square.style.position = 'absolute';
square.style.backgroundColor = 'red';
square.style.top = 0;
square.style.left = left;

console.log('left: ' + left);

这会产生一个正确覆盖的红色框,但它居中而不是设置在左侧。

显示渲染输出

我会在 html 中建议一种不同的方法,通过使用picture<\/code>元素来包裹红色方块。

例如,

html<\/code> :

<div class="center-flex">
    <picture>
        <img id="revealImage">
    </picture>
</div>

我认为你犯了一个小错误(如果我没有弄错的话):

似乎这是错误的:

square.style.left = left;

做:

square.style.left = 0;

这样对吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM