如何根据屏幕尺寸更改<img>源?

时间:2019-08-02 21:48:19

标签: javascript html css

我正在尝试根据显示器的尺寸更改背景图像。它不在服务器上运行。您可以在https://github.com/Umpalompa/Umpalompa.github.io上找到我的所有代码。

我尝试同时使用content:url();background-image: url();;他们俩都没有工作

body {
    overflow: hidden;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.background {
    margin: 0;
    padding: 0;
    z-index: -2;
    height: 100vh;
    width: 100%;
    position: absolute;
    overflow: -moz-hidden-unscrollable;
}

 .background img {
    height: 100vh;
    width: 100%;
}

@media screen and (max-width: 375px){
    .background{
        content:url(./background-imgs/375px.png);
    }
}
@media screen and (max-width: 770px){
    .background{
        content:url(./background-imgs/770px.png);
    }
}
@media screen and (max-width: 1022px){
    .background{
        content:url(./background-imgs/1022.png);
    }
}
@media screen and (max-width: 1290px){
    .background{
        content:url(./background-imgs/1290.png);
    }
}
@media screen and (max-width: 1366px){
    .background{
        content:url(./background-imgs/1366.png);
    }
}

<!-- ---------- background color ---------- -->
<div class="background">
    <img src="./background-imgs/background.png">
</div>

2 个答案:

答案 0 :(得分:2)

您可能希望使用图片元素(请参见documentation),该图片元素将允许您为不同的设备宽度指定不同的图像源。

您使用的content是不正确的,并且在<img>元素上指定背景图像也没有意义-除非图像具有透明部分,否则背景图像将不会t显示它会被实际图像隐藏。您无法使用CSS更改<img>标签的src。

也就是说,如果您真正想要的是用于装饰而不是内容的背景图像,那么您将需要在非<img>元素上使用背景图像,这样您就可以摆脱<img>标签,然后您的css将类似于:

.background{
    background-image: url(./background-imgs/1366.png);
}
    
@media screen and (max-width: 375px){
    .background{
        background-image: url(./background-imgs/375px.png);
    }
}
@media screen and (max-width: 770px){
    .background{
        background-image: url(./background-imgs/770px.png);
    }
}
@media screen and (max-width: 1022px){
    .background{
        background-image: url(./background-imgs/1022.png);
    }
}
@media screen and (max-width: 1290px){
    .background{
        background-image: url(./background-imgs/1290.png);
    }
}

答案 1 :(得分:1)

var backgrounds = document.getElementsByClassName("background");
var height = screen.height;
var width = screen.width;

//do calculation here to determine source based off height and width

for(var x = 0; x < backgrounds.length; x++){
    backgrounds[x].setAttribute("src", "YourSourceHere");
}

由于它是一个属性,一旦确定了适当的来源,就可以使用setAttribute对其进行更改。您还可以使用:

backgrounds[0].setAttribute("src", "YourSourceHere"); 

因为我假设您只有一个实际背景。可能因为这个原因考虑使用ID?