我需要创建一个全屏背景。因此,这个方法可以实现:
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
我想加载一张很大的背景图片(大约2000像素宽),但我认为这种解决方案不太好,因为移动设备也会加载这张大图。
我尝试根据屏幕大小来加载图片:
jQuery(document).ready(function($) {
var win = $(window);
win.resize(function() {
var win_w = win.width(),
win_h = win.height(),
$bg = $("#bg");
// Load narrowest background image based on
// viewport width, but never load anything narrower
// that what's already loaded if anything.
var available = [
1024, 1280, 1366,
1400, 1680, 1920,
2560, 3840, 4860
];
var current = $bg.attr('src').match(/([0-9]+)/) ? RegExp.$1 : null;
if (!current || ((current < win_w) && (current < available[available.length - 1]))) {
var chosen = available[available.length - 1];
for (var i=0; i<available.length; i++) {
if (available[i] >= win_w) {
chosen = available[i];
break;
}
}
// Set the new image
$bg.attr('src', '/images/bg/' + chosen + '.jpg');
}
// Determine whether width or height should be 100%
if ((win_w / win_h) < ($bg.width() / $bg.height())) {
$bg.css({height: '100%', width: 'auto'});
} else {
$bg.css({width: '100%', height: 'auto'});
}
}).resize();
});
所以我需要一个像这样的图像元素:
<img id="bg" src="" style="position: fixed; left: 0; top: 0" />
但这并不是真正的背景(就像第一个解决方案)。是否可能将jquery脚本调整为html背景url?或者有没有更简单的解决方案?
我还想先加载图片,然后再淡入网站......我想我需要jQuery的.load()函数;但我不知道如何将其放入脚本中......