我有一个背景图像和其他一些元素是绝对的。
当我调整浏览器大小时,我希望绝对元素调整自己的大小并保持其比例。
<div style="position:relative">
<div style="background: transparent url('http://via.placeholder.com/600x300') no-repeat;
width: 100%; height: 300px; background-size: contain
"></div>
<div style="width : 100px;height : 75px;position : absolute; background: green;top : 50px;"></div>
<div style="width : 100px;height : 75px;position : absolute; background: red;top : 100px;"></div>
</div>
或 https://jsfiddle.net/2sx7nw5d/4/
有什么想法吗?我可以只使用CSS或JavaScript
当你说你想要元素的大小时,你具体是什么意思?它们应该变大/变小吗?保持与页面的相对大小相同?
如果您希望它们与页面保持相同的相对大小,则可以使用 vw 或 vh 单位。喜欢宽度:20vw;高度:8vw;
如果你想将比例保持在固定比例内,你可以使用填充,如宽度:300px;底部填充: 75%;<-将始终是宽度的75%。
如果你的元素中有内容,这是行不通的,那么你最好只使用 JavaScript 计算高度。
一些研究后想出的。不确定它是否符合您的要求。
以下是 HTML 标记。
<div style="position:relative">
<div style="background: transparent url('http://via.placeholder.com/600x300') no-repeat;
width: 100%; height: 300px; background-size: contain
"></div>
<div style="width : 100px;height : 75px;position : absolute; background: green;top : 50px;" class="dyn" data-defaultwidth="" data-defaultheight=""></div>
<div style="width : 100px;height : 75px;position : absolute; background: red;top : 100px;" class="dyn" data-defaultwidth="" data-defaultheight=""></div>
</div>
所需的 jQuery 片段如下所示。
$(document).ready(function(){
var oldWidth = parseInt($(window).width());
var oldHeight = parseInt($(window).height());
$("div.dyn").each(function(){
$(this).attr("data-defaultwidth", $(this).css("width"));
$(this).attr("data-defaultheight", $(this).css("height"));
});
var resizeTimer;
$(window).on('resize', function(){
if (resizeTimer) {
clearTimeout(resizeTimer); // clear any previous pending timer
}
resizeTimer = setTimeout(function() {
resizeTimer = null;
var newWidth = parseInt($(window).width());
var newHeight = parseInt($(window).height());
$("div.dyn").each(function(){
var thisWidth = parseInt($(this).data("defaultwidth"));
var thisHeight = parseInt($(this).data("defaultheight"));
console.log(thisWidth * newWidth / oldWidth);
$(this).css("width", (thisWidth * newWidth / oldWidth));
$(this).css("height", (thisHeight * newHeight / oldHeight));
});
oldWidth = newWidth;
oldHeight = newHeight;
}, 50);
});
});
https://jsfiddle.net/pktk8obb/39/