如何在选择匹配的响应图像文件时替换 div 的背景图像?

How to replace a background image of a div, while choosing the matching responsive image file?

我有一个带有响应式背景图片的网站 div

我通过 @media 查询选择要拍摄的图像尺寸。

代码中有问题的 div 的 ID 为 banner-div

HTML:
<div id="header-div">
    <div id="background-clipped-div">
        <div id="banner-div">
            <div id="scroll-down-div" onclick="scrollToMainContent()">
                <i class="fas fa-angle-down"></i>
            </div>
        </div>
    </div>
</div>
CSS:
@media only screen and (max-width: 480px) {
    #banner-div {
        background-image: url(images/background-1-small.png);
    }
}

@media only screen and (max-width: 768px) {
    #banner-div {
        background-image: url(images/background-1-medium.png);
    }
}

@media only screen {
    #banner-div {
        background-image: url(images/background-1-big.png);
    }
}

问题:

如果我现在想要 swap/replace 图像,例如通过在多个不同图像之间不断变化的背景图像,我将如何做到这一点同时尊重给定分辨率的正确图像?

假设我在 images 文件夹中有以下图片:

我知道如何替换JavaScript中当前图片的路径,但是我 没有找到替换所有 @media 查询的方法。

您可以为此使用 matchMedia。 我会这样做: - 每个图像容器都将其响应变体设置为数据属性,以便我们可以在每个断点的 javascript 中访问它们:

var $elements = $(".element");
var mqls = [ // list of window.matchMedia() queries
    window.matchMedia("(min-width: 860px)"),
    window.matchMedia("(max-width: 600px)"),
    window.matchMedia("(max-width: 500px)")
]
 
for (var i=0; i<mqls.length; i++){ // loop through queries
    mediaqueryresponse(mqls[i]) // call handler function explicitly at run time
    mqls[i].addListener(mediaqueryresponse) // call handler function whenever the media query is triggered
}

function mediaqueryresponse(mql){
    // check which breakpoint we're in and send the parameter "big", "medium" or "small" to the setBakground function
    if (mqls[0].matches){
     setBackground("big")
    }
    if (mqls[1].matches){
     setBackground("medium")
    }
    if (mqls[2].matches){
     setBackground("small")
    }
}

function setBackground (size) {
  // Loop through each element that needs to have the responsive background images and change the background image based on the current breakpoint
  $elements.each(function() {
   $(this).css({
      "background-image": "url("+$(this).attr("data-"+size)+")"
    })
  })
}
.element {
  width: 400px;
  height: 400px;
  background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<div class="element" data-big="//placehold.it/400x400?text=Big1" data-medium="//placehold.it/300x300?text=Medium1" data-small="//placehold.it/200x200?text=Small1"></div>

<div class="element" data-big="//placehold.it/402x402?text=Big2" data-medium="//placehold.it/302x302?text=Medium2" data-small="//placehold.it/202x202?text=Small2"></div>

编辑:对于 vanilla js 和 jquery 之间的混合感到抱歉。我从网站上复制了第一部分,然后用 jquery.

添加了最后一部分

EDIT2:Link 到 JS fiddle 来测试它的响应能力: https://jsfiddle.net/q30u5o7j/