每次页面加载时我都会尝试更改背景图片。该功能工作正常,但我还希望在移动用户的屏幕宽度小于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;
答案 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());