日期:2014-05-16  浏览次数:20404 次

求解!JS制作全屏背景图思路!!!
最近在折腾一个项目,在做登录页面。想用全屏图片来当背景。于是刚开始的思路认为只要将图片设置成 width:100%;  height:100%; 然后就可以了,发现这样做法,会导致图片拉伸。所以我又去了找了一些全背景登录的网站。比如网易的LOFTER 地址:http://www.lofter.com/,发现其页面不管窗口怎样改变和拉伸,图片的位置:1.不会拉伸难看,2.把图片中间的内容放在窗口中间来显示。

所以我就郁闷了,于是又去Google了一下,找到了一个jQuery 写的全背景图插件,也是自适应窗口来改变图片。实现的原理和Lofter基本是差不多的,所以又看了这插件的源码,里面有一些代码和思路不是能理解。实在是太笨,希望各位能帮小弟来说一下这个思路。

插件地址:http://johnpatrickgiven.com/jquery/background-resize/
JS源码地址:http://johnpatrickgiven.com/jquery/background-resize/js/jquery.ez-bg-resize.js

下面本人在把源码贴上,将一些不理解的地方指出,望各位高手帮小弟整理出思路


/******************************************************
    * jQuery plug-in
    * Easy Background Image Resizer
    * Developed by J.P. Given (http://johnpatrickgiven.com)
    * Useage: anyone so long as credit is left alone
******************************************************/

(function($) {
// Global Namespace
    var jqez = {};

    // Define the plugin
    $.fn.ezBgResize = function(options) {

// Set global to obj passed
jqez = options;

// If img option is string convert to array.
// This is in preparation for accepting an slideshow of images.
if (!$.isArray(jqez.img)) {
var tmp_img = jqez.img;
jqez.img = [tmp_img]
}

$("<img/>").attr("src", jqez.img).load(function() {
jqez.width = this.width;
jqez.height = this.height;

// Create a unique div container
$("body").append('<div id="jq_ez_bg"></div>');

// Add the image to it.
$("#jq_ez_bg").html('<img src="' + jqez.img[0] + '" width="' + jqez.width + '" height="' + jqez.height + '" border="0">');

// First position object
        $("#jq_ez_bg").css("visibility","hidden");

// Overflow set to hidden so scroll bars don't mess up image size.
        $("body").css({
            "overflow":"hidden"
        });

resizeImage();
});
    };

$(window).bind("resize", function() {
resizeImage();
});

// Actual resize function
    function resizeImage() {

        $("#jq_ez_bg").css({
            "position":"fixed",
            "top":"0px",
            "left":"0px",
            "z-index":"-1",
            "overflow":"hidden",
            "width":$(window).width()