Javascript 如何相对于图像定位div?
我有一个文件夹页面,其中包含一个网格,其中包含带有信息覆盖的图像 以下是链接: 是否有一种解决方案可以使覆盖div与图像的大小(高度和宽度)完全相同,而无需使用Javascript 如何相对于图像定位div?,javascript,css,reactjs,Javascript,Css,Reactjs,我有一个文件夹页面,其中包含一个网格,其中包含带有信息覆盖的图像 以下是链接: 是否有一种解决方案可以使覆盖div与图像的大小(高度和宽度)完全相同,而无需使用background:url(…) 问题是图像的大小是随机的 这个问题不是重复的,因为它还没有为我解决 以下是每个图像的组件代码: src/component/ImageWithInfos/ImageWithInfos.jsx: // Lazyload import LazyLoad from 'react-lazyload'; //
background:url(…)代码>
问题是图像的大小是随机的
这个问题不是重复的,因为它还没有为我解决
以下是每个图像的组件代码:
src/component/ImageWithInfos/ImageWithInfos.jsx
:
// Lazyload
import LazyLoad from 'react-lazyload';
// Style
import { ImageContainer, ImageSrc, ImageInfoContainer, ImageInfo } from './styles';
// Utils
import PropTypes from 'prop-types';
import { v4 as uuid } from 'uuid';
const ImageWithInfos = ({ height, width, src, title, infos }) => (
<LazyLoad height={height} offset={height + 100}>
<ImageContainer height={height} width={width}>
<ImageSrc src={src} alt={title} />
<ImageInfoContainer>
<ImageInfo main>{title}</ImageInfo>
{infos.map((info) => <ImageInfo key={uuid()}>{info}</ImageInfo>)}
</ImageInfoContainer>
</ImageContainer>
</LazyLoad>
);
ImageWithInfos.propTypes = {
height: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
src: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
infos: PropTypes.array,
};
export default ImageWithInfos;
src/component/ImageWithInfos/index.js
// Style
import styled, { css } from 'styled-components';
export const ImageContainer = styled.div`
height: ${({ height }) => `${height}px`};
width: ${({ width }) => `${width}px`};
position: relative;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
`;
export const ImageSrc = styled.img`
display: block;
object-fit: contain;
width: 100%;
height: 100%;
`;
export const ImageInfoContainer = styled.div`
z-index: 5;
position: absolute;
bottom: 0;
height: 100%;
width: 100%;
opacity: 0;
transition: 1s ease;
background-color: black;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
&:hover {
opacity: 1;
background-color: rgba(0, 0, 0, .7);
scale: 1.1;
}
`;
export const ImageInfo = styled.span`
padding: .2rem 1rem;
color: whitesmoke;
text-align: center;
text-transform: capitalize;
${({ main }) => main && css`
font-weight: 800;
`}
`;
export { default } from './ImageWithInfos';
谢谢你的帮助
顺便说一句:我正在使用react和styled组件,如果它改变了什么…我相信您可以将图像和覆盖层放在同一个div中,并让覆盖层元素覆盖整个父div:
.parent{
位置:相对位置;
}
.覆盖{
位置:绝对位置;
宽度:100%;
身高:100%;
}
寻求代码帮助的问题必须包含在问题中重现所需的最短代码,最好是在堆栈片段中。虽然您提供了一个链接,但如果该链接无效,您的问题对其他将来遇到相同问题的用户将毫无价值。看,我唯一能想到的就是得到图像的原始大小,计算每个图像的比例,并将其应用到图像叠加中@亲爱的电脑怪人。你的观点绝对正确。你也有经验。事实上,对于未来的用户来说,如果网站内容发生变化,这不会有很大的价值。但回答者能否根据自己的经验回答此类问题。谢谢:)给你,一些代码片段…@aktoriukas这可能是一个选项,但没有更简单的解决方案…我已经这样做了,但覆盖div确实适合父级大小,而不是图像大小…我阅读了你添加的代码片段。目前,您的DOM结构如下所示:parentDiv>[img,overlydiv]
,但您正在为parentDiv设置一个固定的高度和宽度。我的想法是parentDiv的高度和宽度应该从img的高度和宽度推断出来。因此,也许您可以将结构复杂化,使其看起来像parentDiv>parentDiv2>[img,overlydiv]
,并将我前面的代码片段应用于parentDiv2