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

标签 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>

最佳答案

您可能想要使用 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/

相关文章:

javascript - 如何替换数组中元素的实例?

javascript - 如何从菜单外的链接触发 Bootstrap 模板 Accordion 样式菜单

jquery - Django 搜索框位于与结果不同的页面上

html - 使 div 行的内容在 bootstrap 中居中

html - 仅使用 CSS 隐藏未选中的单选按钮

javascript - 如果将 alert() 放在开头,为什么只执行 javascript 函数?

javascript - 在生产中保护 SPA 代码的技术方法

html - 如何使标题更宽?

HTML 表格 CSS 在浏览器中的生成方式与在电子邮件中的生成方式不同

php - 简单的 PHP session 错误