我想使用 jquery 在 div(#bg) 中添加图像来创建自动调整大小的网页。到目前为止,我已经这样编码,但是自动调整大小有一些问题。如果我手动将图像添加到 div 则一切正常。如果你能详细说明你的答案,我是 jquery 的新手。提前致谢。
HTML
<div id="bg">
</div>`
CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }`
jQuery
$(window).load(function() {
$('#bg').prepend('<img src="Background.jpg" id="bg" alt="" />')
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});