我想使用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");
});
答案 0 :(得分:0)
我几天前写过一个类似的功能:
<强> HTML 强>
<img src="http://ge.tt/api/1/files/1jN8IzR/0/blob?download" class='bg'>
<强> CSS 强> 不是真的需要
.bg {
position: fixed;
top: 0;
left: 0;
z-index: -1
}
<强> JS 强>
var fitPic = (function() {
var winW = $(window).width(),
winH = window.innerHeight || $(window).height(); // `innerHeight` for mobile safari
$(".bg").each(function() {
var elem = $(this),
elemW = elem.width(),
elemH = elem.height(),
imgW = (elemW * winH) / elemH,
imgH = (elemH * winW) / elemW,
newW = imgH < winH ? imgW : winW,
newH = imgH < winH ? winH : imgH;
this.style.width = newW + "px";
this.style.height = newH + "px";
});
});
$(window).on('load resize', fitPic);