首页 > 解决方案 > 我需要将图像放置在背景图像的底部,并在调整窗口大小时让它们保持原位

问题描述

我有一个背景图像,并且我有其他图像需要保留在背景图像的底部,即使窗口调整大小或屏幕大小不同也是如此。

这是一个 ReactJS 网络应用程序,因此任何 javascript 或 CSS 都可以使用。

CSS:

html {
   background: url(imageInMemory.png) no-repeat center center fixed;
   background-size: contain;
}

Javascript:

// I calculate the ratio for 'background-size: contain'
let A = window.innerWidth;
let B = window.innerHeight;
let W = naturalWidth; // Width of image, I have this hardcoded
let H = naturalHeight; // Height of image, I have this hardcoded
const ratio = Math.min((A/W), (B/H));// this is the ratio to which the image was scaled given the current window size.
// I position images on top of background images where they should be using this new ratio
<div style={{marginTop: ratio * H * .7}}>
    <img src='otherImage'/>
</div>

这适用于某些窗口大小,但有时图像不会位于背景图像的右侧区域之上。

标签: javascriptcssreactjs

解决方案


将此css用于您的div

    position:fixed;
    bottom:0;

推荐阅读