我正在尝试根据显示器的大小更改背景图像。它不在服务器上运行。您可以在 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>
最佳答案
您可能想要使用 picture 元素(参见 documentation ),它允许您为不同的设备宽度指定不同的图像源。
您正在使用 content
不正确,并在 <img>
上指定背景图像元素也没有意义——除非图像有透明部分,否则背景图像不会显示,因为它会被实际图像隐藏。您无法更改 <img>
的 src使用 css 标记。
就是说,如果您真正想要的是用于装饰而非内容的背景图像,那么您会希望在非 <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);
}
}
关于javascript - 如何根据屏幕尺寸更改 <img> 来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333801/