删除特定宽度的背景图像

时间:2014-08-09 18:45:18

标签: javascript jquery css

每次页面加载时我都会尝试更改背景图片。该功能工作正常,但我还希望在移动用户的屏幕宽度小于640px时将背景图像设置为无。我尝试使用screen.width和screen.availWidth,但两者都没有做任何事情。无论屏幕尺寸如何,我的背景图像都会保留。

function changeImg(imgNumber)   {
    var myImages = ["images/bg_images/audi_tt.jpg", "images/bg_images/watercooled.jpg", "images/bg_images/aircooled.jpg"];
    var imgShown = document.body.style.backgroundImage;
    var newImgNumber =Math.floor(Math.random()*myImages.length);
    var windowWidth = window.screen.availWidth;
    if (windowWidth <= 640) {
        document.body.style.backgroundImage = 'none';
    } else if (windowWidth > 640) {
        document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
    }
}
window.onload=changeImg;

1 个答案:

答案 0 :(得分:0)

你可以用这种方式完成所有这些:

function changeImg(imgNumber)   {
    var myImages = ["images/bg_images/audi_tt.jpg", "images/bg_images/watercooled.jpg", "images/bg_images/aircooled.jpg"];
    var newImgNumber =Math.floor(Math.random()*myImages.length);
    var windowWidth = $(window).width();
    if (windowWidth <= 640) {
        $('body').css('background-image', 'none');
    } else if (windowWidth > 640) {
        $('body').css('background-image', 'url('+myImages[newImgNumber]+')');
    }
}
$(window).load(changeImg());