javascript - 使用强制重新加载或导航回主页时,背景图像调整大小不起作用

标签 javascript jquery responsive-design

在我们的网站 www.mydubaitrip.com我有一个脚本可以根据浏览器宽度调整背景图像的大小。我的问题是,每当我尝试按 Ctrl+F5 或导航到酒店页面并返回主页时,背景图像都不会显示无法正确调整大小,我的布局看起来很困惑。但如果我尝试再次按 F5,它现在会相应调整。我无法弄清楚问题出在哪里。

这是我使用的脚本。

    var minWidth = 1024;
var minHeight = 844;
var winRatio = new Array();
var imgReady = new Array();
var orientation = 90;
var debounceId;

var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (isiPad) {
    var minWidth = 980;
}

var readyToRotate = false;
var readyToResize = true;

var miniContentWrapperHeight = 444;

// BACKGROUND TRANSITION 
var theTimer;
var currBanner = -1;
var totalBanner = 0;
var timeWaiting = parseInt(500);
var timeTextTransIn = parseInt(1000);
var timeTextTransOut = parseInt(1000);
var timeTransCross = parseInt(2000);
var timeTransInit = parseInt(0);
var timeTransInterval = parseInt(7000);

var transitioning = false;

$("#homePageMainPanel").css({ "backgroundColor": "black" });

var hybridMode = true;
if (($.browser.mozilla && $.browser.version == "5.0") ||
    $.browser.msie && $.browser.version == "9.0") {
    //hybridMode = false;
}

//$("html").css({ "overflow": "hidden" });


function updateOrientation() {

    // scroll and hide address bar for iPhone landscape
    setTimeout(function() { window.scrollTo(0, 1) }, timeWaiting);

    if (window.orientation != undefined)
        orientation = Math.abs(window.orientation);

    resizeBackground();
}

$(window).load(function() {

    resizeBackground();

    if (!($.browser.msie && $.browser.version == "6.0")) {
        var lang = $('meta[name="language"]').attr("content");
        if ((lang == "ar") || (lang == "ir")) {
            $(".carouselShadow").css('background', 'url(/media/images/fg_ar_text_bg.png) no-repeat');
        }
        else {
            $(".carouselShadow").css('background', 'url(/media/images/fg_text_bg.png) no-repeat');
        }
    }
});

$(document).ready(function() {

    if (typeof BackgroundInfo != 'undefined' && BackgroundInfo.length > 0) {
        $("#carousel").append("<img src=\"" + BackgroundInfo[0].Src + "\" alt=\"" + BackgroundInfo[0].Alt + "\" />");
    }

    if ($(window).height() > $(document).height() - $("#bottomLayer").height()) {
        $("#bottomLayer").css({ 'position': 'absolute', "top": parseInt($(window).height() - $("#bottomLayer").height()) });
        $("#carousel img").height($(window).height() - $("#bottomLayer").height());
        //alert($("#bottomLayer").offset().bottom);
        $(".bookPanel").css({ 'position': 'relative', "bottom": parseInt($(".bookPanel").height() - $("#carousel").height() + 28) });
        $(".carouselShadow").css({ 'position': 'relative', "bottom": parseInt($(".carouselShadow").height() - $("#carousel").height()+20) });

        setTimeout(function() {
            $("#bottomLayer").css({ "position": "relative", "top": parseInt($(window).height() - $("#bottomLayer").height()) });
        }, 500);

        setTimeout(function() {
        $(".bookPanel").css({ "position": "relative", "bottom": parseInt($(".bookPanel").height() - $("#carousel").height() + 28) });
        }, 500);

        setTimeout(function() {
        $(".carouselShadow").css({ "position": "relative", "bottom": parseInt($(".carouselShadow").height() - $("#carousel").height()+20) });
        }, 500);

    }

    //in case the navigation height is longer than prefixed minheight, adjust minheight=navigation height
    var homepageHeight = $("#homePageMainPanel").height() + $("#bottomLayer").height();
    if (homepageHeight > minHeight)
        minHeight = homepageHeight;


    //this is only for mobile safari on ipad/iphone
    window.onorientationchange = function() {
        window.scrollTo(0, 1);  // to prevent jumpy and blinky page transitions
        updateOrientation();
    }

    $(window)
        .resize(function() {
            if (readyToResize) {
                clearTimeout(debounceId);
                debounceId = setTimeout(resizeEvent, 500);
            }
        })
        .load(function() {
            // scroll and hide address bar for iPhone landscape
            setTimeout(function() { window.scrollTo(0, 1) }, timeWaiting);
        });

    initRotateBanner();
});

var winWidth = $(window).width();
var winHeight = $(window).height();

var winNewWidth = -1;
var winNewHeight = -1;

function resizeEvent() {
    // JL: Hack to prevent IE 7,8 to have infinite loop when window.resize event
    winNewWidth = $(window).width();
    winNewHeight = $(window).height();
    if (winWidth != winNewWidth || winHeight != winNewHeight) {
        clearTimeout(debounceId);
        resizeBackground();
    }
    winWidth = winNewWidth;
    winHeight = winNewHeight;
}

function initRotateBanner() {

    $('#carousel img').eq(0).one('load', function() {
        if (readyToRotate = true) {
            if (typeof BackgroundInfo != 'undefined' && BackgroundInfo.length > 0) {
                $.each(BackgroundInfo, function(i, v) {
                    if (i > 0) {

                        $("#carousel").append("<img src=\"" + BackgroundInfo[i].Src + "\" alt=\"" + BackgroundInfo[i].Alt + "\" />");
                    }
                });
                initBackgroundImageReady();
            }
            imgReady[0] = true;
            window.setTimeout("rotateBanner('init')", timeTransInit);
        }
        //$('#background').children("img").show();
        //$('#background').children("img").css({ 'opacity': '1' });
        resizeBackground();

    }).each(function() {
        // $(this).load();
    });

    /// assign each background text accordingly
    var index = 0;
    $('.carouselContentContainer').each(function() {
        $(this).attr('id', 'text_box_' + index);
        index++;
    });
}

function initBackgroundImageReady() {
    $('#carousel').children("img").each(function() {
        //assign each background id accordingly
        $(this).attr('id', 'img_box_' + totalBanner);

        // flag correspondingly when bg images is loaded
        imgReady[totalBanner] = false;
        $(this).one('load', function(event) {
            var id = $(this).attr('id');
            var idArr = new Array();
            idArr = id.split('_');
            var index = idArr[idArr.length - 1];

            //console.log(index + "loaded");
            imgReady[index] = true;
            resizeBackground();
        });

        //$(this).load();
        totalBanner++;
    });
}

function resizeBackground() {

    readyToResize = false;
    $('html').css({ 'overflow': 'hidden' });
    $("#carousel").children("img").each(function() {

        var oriWidth = $(this).width('');
        var oriHeight = $(this).height('');

        var bgWidth = $(window).width();
        if (bgWidth < minWidth)
            bgWidth = minWidth;

        var bgHeight = bgWidth / oriWidth * oriHeight;
        if (oriHeight < bgWrapperHeight)
            bgWrapperHeight = oriHeight;

        $(this).css({ 'position': 'absolute', 'width': bgWidth, 'height': bgHeight });

    });

    //start with window height & width
    var bgWrapperHeight = $(window).height();
    var bgWrapperWidth = $(window).width();

    // if vertical scrollbar exists, accommodate the scrollbar width (16px)
    if ($.browser.webkit == true) {
        ////$("#log").prepend(document.body.scrollHeight + " : " + document.body.clientHeight + "<br />");
        if (document.body.scrollHeight < document.body.clientHeight)
            bgWrapperWidth = $(window).width() - 16;  // accomdate the scroll bar width (16px)
        else
            bgWrapperWidth = $(window).width();
    }
    else {
        ////$("#log").prepend($(document).height() + " : " + $(window).height() + "<br />");
        if ($(window).height() < $(document).height())
            bgWrapperWidth = $(window).width() - 17;  // 
        else
            bgWrapperWidth = $(window).width();
    }


    // for screen size > min height (hp-navigation) but < min background image size, adjust to fit without scroller
    if (bgWrapperHeight + $('#bottomLayer').height() > $(window).height()) {
        bgWrapperHeight = $(window).height() - $('#bottomLayer').height();
    }

    //wrapper height should not go lower than navigation height
    if (bgWrapperHeight < $('#bookPanel').height())
        bgWrapperHeight = $('#bookPanel').height();

    //wrapper width should not go lower than min width
    if (bgWrapperWidth < minWidth)
        bgWrapperWidth = minWidth;

    // set #hp-content-wrapper height
    $('#homePageMainPanel').css({ 'height': bgWrapperHeight, 'width': bgWrapperWidth });
    $('#carousel').css({ 'height': bgWrapperHeight, 'width': bgWrapperWidth });
    $('#bottomLayer').css({ 'width': bgWrapperWidth });

    $('html').css({ 'overflow': 'auto' });

    //TODO: better way to center align bg image!
    //var nn = 0;
    // vertically middle align background
    $("#carousel").children("img").each(function() {
        // IF document height (minus footer height) is more than background image, 
        //    Expand Background Image Vertically!
    if (($(document).height() - $('#bottomLayer').height()) >= $(this).height()) {
            var newHeight = $(document).height() - $('#bottomLayer').height();
            var newWidth = Math.round((newHeight / $(this).height()) * $(this).width());

            var offsetX = ((bgWrapperWidth - newWidth) / 2);
            $(this).css({ 'position': 'absolute', 'left': offsetX, 'width': newWidth, 'height': newHeight });
            // $("#log").prepend($(document).height() + " : " + $('#footer').height() + "<br />");
            // Reset back the image top position to 0;
            $(this).css({ 'position': 'absolute', 'top': 0 });
        }
        else { //TODO: figure out what contributes to offset??
            var newWidth = $(document).width();
            var newHeight = Math.round((newWidth / $(this).width()) * $(this).height());
            var offsetX = ((bgWrapperWidth - newWidth) / 2);
            // Reset back the image left position to 0;
            $(this).css({ 'position': 'absolute', 'left': 0, 'width': newWidth, 'height': newHeight });
            // $(this).css({ 'position': 'absolute', 'left': 0, 'width': '100%', 'height': '' });


            if (bgWrapperHeight > $('#bottomLayer').position().top) {
                var offsetY = ((bgWrapperHeight - $(this).height()) / 2);
                $(this).css({ 'top': offsetY });
            }
            else {
                var offsetY = (($('#bottomLayer').position().top - $(this).height()) / 2);
                $(this).css({ 'top': offsetY });
            }
        }
    });


    //$(".bookPanel").css({ 'position': 'absolute', "top": parseInt($("#carousel").height()) });
    $('#bottomLayer').css({ 'position': 'absolute', 'top': $("#carousel").height() });
    $(".bookPanel").css({ "bottom": parseInt($(".bookPanel").height() - $("#carousel").height() + 28) });
    $(".carouselShadow").css({ 'position': 'relative', "bottom": parseInt($(".carouselShadow").height() - $("#carousel").height()) });
    //when having vertical scroll bar
    //known issue: does not work for IE screen onresize, only works onload
    if ($(window).height() != $(document).height()) {
        //$("#roomreservations").html($(window).width() + ":" + $(document).width() + ":" + minWidth);
        if ($(document).width() == minWidth && ($(window).width() != $(document).width())) {
            //show horizontal scrollbar (by default)
        }
        else {
            //otherwise hide horizontal scrollbar
            $('html').css({ 'overflow-x': 'hidden' });
        }
    }
    setTimeout('checkWidth(' + bgWrapperWidth + ')', 500);

    readyToResize = true;
}

function checkWidth(bgWrapperWidth) {
    $('#homePageMainPanel').width('100%');
    $('#bottomLayer').width('100%');
    $('#carousel').width($(document).width());

    $("#carousel").children("img").each(function() {
    if (($(document).height() - $('#bottomLayer').height()) >= $(this).height()) {
            // Resize the image height to $("#background") height, as the image should fill from the top till the footer
            $(this).css({ 'width': (($("#carousel").height() / $(this).height()) * $(this).width()), 'height': $("#carousel").height() });
        }
    });
}

function positionFooter() {
    return null;
    var footerPosition = $('#carousel').height() - $('#bottomLayer').height() + 1;
    if ($('#carousel').height() < minHeight) {
        footerPosition = minHeight - $('#carousel').height() + 1;
    }

    $('#carousel').css({ 'position': 'absolute', 'top': footerPosition });

    $('html').css({ 'overflow': 'auto' });

    $("#homePageMainPanel").css({ 'height': $('#carousel').height() });

}

var waitingTimeout;
function rotateBanner(param) {

    var nextBanner = 0;
    nextBanner = parseInt(currBanner) + 1;

    if (nextBanner >= totalBanner) { nextBanner = 0; }

    // wait until next bg image is fully loaded
    if (imgReady[nextBanner] != true) {
        waitingTimeout = window.setTimeout("rotateBanner('waiting')", timeWaiting);
        return false;
    }

    clearTimeout(waitingTimeout);



    transitionStart();

    // cross fade
    if (currBanner > -1) {

        if (hybridMode) {
            window.setTimeout("changeClass('quality','speed')", 500);
            window.setTimeout("changeClass('speed','quality')", 1500);
        }

        fadeBgImg('#text_box_' + String(currBanner), 0, 500);

        window.setTimeout("fadeBgImg('#img_box_" + String(currBanner) + "',0," + 1000 + ")", 500);
        window.setTimeout("fadeBgImg('#img_box_" + String(nextBanner) + "',1," + 1000 + ")", 500);
        window.setTimeout("fadeBgImg('#text_box_" + String(nextBanner) + "',1," + 1000 + ",true)", 1500);

        window.setTimeout("transitionComplete()", 2500);

    }
    else {

        if (hybridMode) {
            changeClass('quality', 'speed');
            window.setTimeout("changeClass('speed','quality')", 1000);
        }
        fadeBgImg("#img_box_" + String(nextBanner), 1, 1000);
        window.setTimeout("fadeBgImg('#text_box_" + String(nextBanner) + "',1," + 1000 + ",true)", 1000);

        window.setTimeout("showShadow()", 1000);

        window.setTimeout("transitionComplete()", 2000);
    }
    currBanner = nextBanner;

}

function nextPaging(nextBanner) {
    $('#carousel #paging ul li').each(function() {
        if ($(this).attr('id') == 'paging_item_' + nextBanner) {
            $(this).addClass("active");
        }
        else {
            $(this).removeClass("active");
        }
    });
}

function changeClass(from, to) {
    $("#carousel").removeClass(from).addClass(to);
}

function fadeBgImg(id, inout, duration, triggerTimer) {
    $(id).stop(true, true);


    if (inout == 1) {
        $(id).fadeIn(duration);
    }
    else {
        $(id).fadeOut(duration);
    }

    //$(id).animate({ 'opacity': inout }, duration);
    if (triggerTimer == true) {
        window.clearTimeout(theTimer);
        if (totalBanner > 1) {
            theTimer = window.setTimeout("rotateBanner()", timeTransInit + timeTransInterval);
        }
    }
}

function transitionStart() {
    transitioning = true;
}

function transitionComplete() {
    transitioning = false;
}


function Timer(callback, delay) {

    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    this.resume = function() {
        start = new Date();
        timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
}

var waitingTimeout2;
function onBlur() {
    //theTimer.pause();
    clearTimeout(waitingTimeout2);
    if (transitioning) {
        waitingTimeout2 = window.setTimeout("onBlur()", timeWaiting);
        return false;
    }
    window.clearTimeout(theTimer);
};

function onFocus() {
    //theTimer.resume();
    if (totalBanner > 1) {
        window.clearTimeout(theTimer);
        theTimer = window.setTimeout("rotateBanner()", timeTransInit + timeTransInterval);
    }
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
    readyToRotate = true;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
    readyToRotate = true;
}


function showShadow() {
    // Do not fade in shadow png IE8 and below
    if ($.browser.msie && parseInt($.browser.version, 10) <= 8) {
        $(".carouselShadow").delay(1000).show();
    }
    else {
        $(".carouselShadow").delay(1000).fadeIn();
    }
}

最佳答案

虽然您自己构建了这个很棒,但有人已经用Backstretch解决了您的所有问题。 .

关于javascript - 使用强制重新加载或导航回主页时,背景图像调整大小不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14545849/

相关文章:

javascript - 从另一个对象创建新的且不同的对象的最佳方法

jquery - Bootstrap 弹出窗口中的 Ajax

css - 为什么 CSS 在 Android 上无法正常工作?

css - 到处使用 col-xs-* 是个好习惯吗?

javascript - resolveLocalFileSytemURL 返回 FileError {代码 :5}?

javascript - three.js PointCloud 中的可点击粒子

javascript - 什么样的构造会在 Javascript 中使用注释分隔符 */?

javascript - jQuery 第一次循环没有延迟

javascript - 所有属性都设置为最后一个循环迭代值[为什么?]

html - 使用媒体查询时完美对齐列表