简体   繁体   English

如果屏幕分辨率宽度> 1028,则添加背景img

[英]Adding background img if screen resolution width >1028

Hi guys, 嗨,大家好,

I'm fairly new to javascript. 我对javascript很陌生。 I have a pretty simple script I wrote to add a background image if the screen resolution width is bigger than 1028px. 如果屏幕分辨率宽度大于1028px,我有一个非常简单的脚本来添加背景图像。

Unfortunately, after trying this (on another computer, with 800x600 resolution), it doesn't work. 不幸的是,在尝试此操作(在另一台分辨率为800x600的计算机上)后,此方法不起作用。

I'm not looking to stretch the image, just simply add it if the screen resolution width is bigger than or equal to 1024. 我不希望拉伸图像,只是在屏幕分辨率宽度大于或等于1024时简单地添加它。

Here is the code: 这是代码:

    <SCRIPT language="JavaScript">
    <!--
    document.write('<style type="text/css">div#container_header_body {background-image:url(\'');
    if (screen.width<1024)
    {
     document.write('none;');
    }
    else
    {
      document.write('images/mmmgirl.png');
    }
    document.write('\');</style>');
    //-->
    </SCRIPT>

<link rel="stylesheet" type="text/css" href="stylesheet.css" />

Can anybody give me some insight into what I'm doing wrong? 谁能给我一些我做错事情的见解?

Thanks so much. 非常感谢。 I've already learned a LOT from this place. 我已经从这个地方学到了很多。

- - Andrew - - 安德鲁

No need for JavaScript, just use a CSS media query : 无需JavaScript,只需使用CSS媒体查询

@media all and (min-width: 1024px) {
    background-image: url(images/mmmgirl.png);
}

Try this jsfiddle : 试试这个jsfiddle

var screenWidth = screen.width,
    container = document.getElementById('container_header_body');

console.log(screenWidth);

if (screenWidth > 1024) {
     container.style.backgroundImage = 'url(http://oddanimals.com/images/lime-cat.jpg)';
} else {
    container.style.backgroundImage = 'none';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM