算法调整图像的规模,以浏览器的大小

Algorithm for adjust image scale to browser sizes

本文关键字:浏览器 调整 图像 算法      更新时间:2023-09-26

我需要一个CSS background的算法/数学计算。当我们在为我们的页面编写样式时,有时我们使用background-image作为元素的背景样式和语法是这样的:background: url('img.jpg') center top;这种样式提供了浏览器在浏览器大小改变时自动改变背景图像的大小,并且我们只能看到我们样式元素的中心侧。但也许我们需要一个图像(在我的情况下),没有背景属性,像这样:<img src="img.jpg">。最后一个例子是我的问题。我想改变它自动,将只显示像css的背景属性图像的中心侧。现在,我想用javascript来解决这个问题,但我需要一个算法从浏览器。如何根据浏览器大小调整图像大小,如何只显示图像的中心…

所以我的意思是如何获得相同的结果在javascript从background-position:center;

你在找这样的东西吗?

html:

full image:<br/>
<img src="http://lorempixel.com/400/200"></img><br/>
smaller, centered image:<br/>
<div class="container"><img src="http://lorempixel.com/400/200"></img></div>
css:

.container{
    width: 200px;
    height: 150px;
    text-align: center;
    overflow: hidden;
}
.container img{
    position: relative;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -200px;
}

Css可以实现很多,你不必总是使用js。如果你想改变图像,你只需要改变margin-left/margin-top属性为图像宽度/高度的一半。