我需要创建一个整页背景。因此这会起作用:
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-background-url? 或者有人知道更简单的解决方案吗?
我还想先加载图像 (!),然后淡入淡出网站……我想我需要 jQuery 的 .load() 函数;但我不知道如何将其放入脚本中...
最佳答案
使用响应式设计。即 css-only 解决方案:
body {
background-image: url("lg_image.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
}
@media (max-width: 767px) {
body {
background-image: url("xs_image.png");
}
}
@media (min-width: 768px) and (max-width: 992px) {
body {
background-image: url("sm_image.png");
}
}
@media (min-width: 993px) and (max-width: 1200px) {
body {
background-image: url("lg_image.png");
}
}
@media (min-width: 1201px) {
body {
background-image: url("xl_image.png");
}
}
不支持 CSS3 的浏览器将显示 lg_image.png,因此可以正常降级。
关于jquery - 加载适当大小的整页背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044807/