我有一个网站,该网站的 div
具有响应式背景图片。
我通过 @media
查询选择要拍摄的图像大小。
代码中有问题的 div 具有 id banner-div
。
<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);
}
}
问题:
如果我现在想交换/替换图像,例如通过在多个不同图像之间使用不断变化的背景图像,我将如何做到这一点,同时尊重给定分辨率的正确图像?
假设我在 images
文件夹中有以下图片:
- background-1-small.png
- background-1-medium.png
- background-1-big.png
- background-2-small.png
- background-2-medium.png
- background-2-big.png
我知道如何用 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:链接到 JS fiddle 以测试它的响应能力: https://jsfiddle.net/q30u5o7j/
关于javascript - 如何在选择匹配的响应图像文件时替换 div 的背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57919723/