我编写了这个脚本,以便在调整窗口大小时,我网站上的壁纸(对象的图片)定位正确并居中。现在它按我想要的方式工作,但只有当窗口调整大小时,在正常情况下,当窗口没有调整大小时,它显然无法获得 img 元素的宽度,因为它不会减去它的一半左侧的 CSS 属性。我如何得到它?
HTML:
<div class="wallpaper" id="wallpaper">
<img src=@bgImage.img id="wallpaperImg" style="height:100%; width: auto; position: fixed;">
</div>
JS:
<script type="text/javascript">
var screenWidth;
var screenHight;
var totalHeight;
var aspectRatio;
var blah = false; //Ugly hack
var navbarSize = 41;
var wallpaper = $("#wallpaperImg");
function getAspectRatio(h,w){
return (h-1)/w; //Ugly hack
}
function resizeWallpaper(w,h){
if(typeof(aspectRatio)==='undefined') aspectRatio = @bgImage.aspectRatio; //delivered by server framework
totalHeight = (h-navbarSize).toString() + 'px';
wallpaper.css("height",totalHeight);
wallpaper.css("width","auto");
wallpaper.css("left",(w/2)-(wallpaper.width()/2)+'px');
wallpaper.css("top",'41px');
if(getAspectRatio(wallpaper.height(),wallpaper.width()) > aspectRatio && blah){
wallpaper.css("width",(w).toString() + 'px')
wallpaper.css("height","auto")
wallpaper.css("top",((h/2)-(wallpaper.height()/2))+20.5+'px');
wallpaper.css("left",'0px');
}
}
resizeWallpaper($(window).width(),$(window).height());
blah = true;
$(window).resize(function() {
resizeWallpaper($(window).width(),$(window).height());
});
</script>
快速上传我正在谈论的内容:网站