如何按比例调整绝对元素的大小?

How to proportionally resize absolute elements?

我有一张背景图片和其他一些绝对定位的元素。

当我调整浏览器大小时,我希望绝对元素自行调整大小并保持其比例。

<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

当您说要调整元素的大小时,具体指的是什么? 他们应该得到 bigger/smaller 吗?与页面保持相同的相对大小?

如果您希望它们与页面保持相同的相对大小,您可以使用 vw 或 vh 单位。像 宽度:20vw; 身高:8vw;

如果你想将比例保持在一个固定比例内,你可以使用像这样的填充 宽度:300px; padding-bottom: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/