关闭popify模态并保持页面中的滚动位置

时间:2015-05-21 22:27:11

标签: javascript jquery

我的关闭按钮功能(通过主插件文件下方)刷新到页面顶部;我需要在长垂直滚动页面中保持位置,当单击关闭按钮退出弹出窗口时。

按钮的HTML:

    <a href="" class="closePopup westonClose">X</a>

主要popify插件JS:

// JavaScript Document

/** A modal pop-up.

    Basic usage.

    --------------------------------------------------------------------
    HTML elemets that the plugin will create on document ready.

    <!--
        An overlay that will act as a background for the pop-ups.
        Only one will be added to the DOM.
     -->
    <div id="flyPopifyOverlay" class="flyPopifyHide"><!-- Empty. --></div>

    <!--
        A wrapper element for each pop-up's content.
    -->
    <div class="flyPopifyOverlayContent" class="flyPopifyHide">

    </div>

    --------------------------------------------------------------------
    The following options can be pased to the plugin:

    Option name: default value
    opacity: 1
        The popup's background opacity.

    minY: 0
        The highest the pop-up can follow the scroll vertically
        relative to the document.

    maxY: $(document).height() - popup.height()
        The lowest the pop-up can follow the scroll vertically
        relative to the document.

    --------------------------------------------------------------------
    The pop-up's wrapper element ('.flyPopifyOverlayContent') will respond
    to the following events:

    fly-popify-show:
        Displays the pop-up.

    fly-popify-hide:
        Hides the pop-up.

    There are 2 (two) helper plugin functions: popifyOpen and popifyClose.
    They, respectivley open and close the pop-ups they're invoked on.
    Note that these helper functions can be called on the .flyPopifyOverlayContent
    elements themselves or any descendant elements.

    <code>
        // Popify some content.
        $('#content').popify();

        // Will open the pop-up in which the a elements reside.
        $('#content .comeClass a').popifyOpen();

        // Same as the above.
        $('#content').popifyClose();

        // Will open all pop-ups.
        $('.flyPopifyOverlayContent').popifyOpen();

        // No effect.
        $('body').popifyOpen();
    </code>

*/

var jqPopify = false;
if ('undefined' != typeof jqFly) {
    jqPopify = jqFly;
} else if ('undefined' != typeof jQuery) {  
    jqPopify = jQuery;
}

(function($){
    // Default options.
    var defaultSettings = {
        // The popup's background opacity.
        opacity: 0,

        // The highest the pop-up can follow the scroll vertically.
        minY: 0,
        // The lowest the pop-up can follow the scroll vertically.
        maxY: null // Note that this is just a temp. Will get calculcated for each individual pop-up.
    };

    var inlineStyles = {
        overlay: {
            display: 'none',

            position: 'absolute',
            top: '0',
            left: '0',
            opacity: '0.50',
            background: '#000',
            zIndex: '-100'
        },
        overlayContent: {
            display: 'block',
            opacity:0,
            position: 'absolute',
            top: '0',
            left: '0',
            zIndex: '-100'
        }
    };

    function showLightbox(e) {
        if (!$('#flyPopifyOverlay').hasClass('flyPopifyHide')) {
            return;
        }

        $('#flyPopifyOverlay')
            .removeClass('flyPopifyHide')
            .stop(true)
            .clearQueue()
            .show()
            //.animate({ opacity: 0.53 });

        $(this)
            .removeClass('flyPopifyHide')
            .stop(true)
            .clearQueue()
            .show();
            $(window).scroll();

        onWindowResize();
    };

    function hideLightbox(e) {
        var overlayContent = $(this);

        $(this)
            .addClass('flyPopifyHide')
            .stop(true)
            .clearQueue()
            .animate({ /*opacity: 0 */}, function() {
                $(overlayContent).hide();
            });

        $('#flyPopifyOverlay')
            .addClass('flyPopifyHide')
            .stop(true)
            .clearQueue()
            .animate({ /*opacity: 0*/ }, function() {
                $('#flyPopifyOverlay').hide();
            });
    };

    function onWindowResize(e) {
        $('#flyPopifyOverlay')
            // Pretty simple. What happens when overlay needs to be offseted?
            // Let's say it starts from 100th pixel to allow for navigation menu
            // interaction?
            .width($(document).width())
            .height($(document).height());
    };

    /**
     * onWindowScrollResize()
     *
     * Called when the viewport changes, for both positon (relative to [0,0])
     * and dimensions (width and height).
     */
    function onWindowScrollResize(e) {
        // There shouldn't be more then 1 (one) pop-up opened at a time in general,
        // so don't take into account the posibility of more the 1 opened.
        popup = $('.flyPopifyOverlayContent').not('.flyPopifyHide').first();

        if (!popup.size()) {
            return;
        }

        var toX = 0;
        var toY = 0;

        // Make sure the object is copied, otherwise we're modifing
        // the element's settings variable.
        var settings = popup.data('settings');//$.extend({}, popup.data('settings'));

        // Make sure used settings are correct.
        if (!settings.maxY) {
            settings.maxY = $(document).height() - $(popup).height();
        }
        if (!settings.maxX) {
            settings.maxX = $(document).width() - $(popup).width();
        }

        // Code repeats. It's simply lines.
        // TODO: Come up with a generic center(k1, k2, v1, v2, maxK1, maxK2).
        // k1 represents the line's left most point and k2 right most point.
        // v1 and v2 are the viewport's points (which is a line as well).
        // maxK1 and maxK2 are the bounds.
        // Vertical and horizontal alignemnt of the pop up is identical
        // due to both axis being the same - can be represented as
        // lines on a flat plane.

        // ************ Process horizontal. ************
        // Get the center X relative to the window's width.
        if (popup.width() < $(document).width()) {
            var x = parseInt($(window).width()/2);
                x -= parseInt(popup.width()/2);
                toX = $(window).scrollLeft() + x;

            if (popup.width() > $(window).width()) {
                var vpLeftX = $(window).scrollLeft();
                var vpRightX = vpLeftX + $(window).width();
                var pLeftX = parseInt(popup.css('left'));
                var pRightX = pLeftX + popup.width();

                if (vpLeftX < pLeftX) {
                    toX = $(window).scrollLeft();
                } else if (vpRightX > pRightX) {
                    toX = vpRightX - popup.width();
                } else {
                    toX = pLeftX;
                }
            }

            // Upper bound.
            if (settings.minX > toX) {
                toX = settings.minX;
            }
            // Lower bound.
            if (settings.maxX <= toX) {
                //toX = $(document).height() - popup.height() - 1;
                toX = settings.maxX - 1;
            }
        }
        // ************ END process horizontal. ************

        // ************ Process vertical. ************
        // If the height of the popup is less then the document,
        // only then it will be centered.
        if (popup.height() < $(document).height()) {
            // Get the center Y relative to the viewport's height.
            var y = parseInt($(window).height()/2);
                y -= parseInt(popup.height()/2);
                toY = $(window).scrollTop() + y;

            if (popup.height() > $(window).height()) {
                var vpTopY = $(window).scrollTop();
                var vpBottomY = vpTopY + $(window).height();
                var pTopY = parseInt(popup.css('top'));
                var pBottomY = pTopY + popup.height();

                if (vpTopY < pTopY) {
                    toY = $(window).scrollTop();
                } else if (vpBottomY > pBottomY) {
                    toY = vpBottomY - popup.height();
                } else {
                    toY = pTopY;
                }
            }

            // Upper bound.
            if (settings.minY > toY) {
                toY = settings.minY;
            }
            // Lower bound.
            if (settings.maxY <= toY) {
                //toY = $(document).height() - popup.height() - 1;
                toY = settings.maxY - 1;
            }
        }
        // ************ END process vertical. ************


        popup
        .stop(true)
        .clearQueue()
        .animate({ top: toY, left: toX, opacity: 1 }, 500);
    };

    $.fn.popifyOpen = function(options) {
        var settings = $.extend(true,
            // No settings for popifyOpen.
            {},
            // User supplied.
            options
        );

        $(this).trigger('fly-popify-show');
        $('#flyPopifyOverlay , .flyPopifyOverlayContent').css({'z-index':9998,opacity:1});
        $('#flyPopifyOverlay ').css({opacity: 0.5});

        return this;
    };

    $.fn.popifyClose = function(options) {
        var settings = $.extend(true,
            // No settings for popifyClse.
            {},
            // User supplied.
            options
        );

        $(this).trigger('fly-popify-hide');
        $('#flyPopifyOverlay , .flyPopifyOverlayContent, .closePopup').css({'z-index':-100,display:'none', opacity:0});
            window.location.reload();
        return this;
    };

    $.fn.popifyRefresh = function() {
        onWindowScrollResize();
        return this;
    };

    $.fn.popifyIsOpen = function() {
        if (1 == $(this).parents('.flyPopifyOverlayContent:first').size()) {
            return !$(this).parents('.flyPopifyOverlayContent:first').hasClass('flyPopifyHide');
        };

        return false;
    }
;   
    $.fn.popify = function(options) {
        // Merge (deep) user settings to defaults and produce
        // the global settings for this invokation.
        var settings = $.extend(true,
            defaultSettings,
            // User supplied.
            options
        );

        this.each(function(i, content) {
            var overlayContent = null;
            // Copy global settings.
            var tempSettings = $.extend({}, settings);

            // Determine maximum Y.
            if (tempSettings.maxY) {
                tempSettings.maxY = tempSettings.maxY - $(content).height();
                if (0 >= tempSettings.maxY ) {
                    tempSettings.maxY = 1;
                }
            }

            // Wrap in jQuery object.
            content = $(content);
            // Save the settings.
            content
                .detach();

            $('<div class="flyPopifyOverlayContent flyPopifyHide"></div>')
                .appendTo('body')
                .append(content);

            // Figure out the parent overlay element, since it has not id just use parent().
            overlayContent = $(content.parent());

            // Set initial opacity to 0.
            overlayContent
                .data('settings', tempSettings)
                .css(inlineStyles.overlayContent)
                // Setup default hide/show events.
                .bind('fly-popify-show', showLightbox)
                .bind('fly-popify-hide', hideLightbox);
        });

        $(window).trigger('resize');

        return this;
    };

    // These are the global actions and event handlers that have
    // to be carried out / defined before the plugin is invoked.
    $(document).ready(function(e){

        // If not already added, add the global overlay element.
        $('body').append('<div id="flyPopifyOverlay" class="flyPopifyHide"><!-- Empty. --></div>');
        $('#flyPopifyOverlay')
        .css(inlineStyles.overlay);

        $('#flyPopifyOverlay').bind('click', function(e) {
            $('.flyPopifyOverlayContent').not('.flyPopifyHide')
                .trigger('fly-popify-hide');
                window.location.reload(true);
        });

        $(window)
            .bind('resize', onWindowResize)
            .bind('resize scroll', onWindowScrollResize);
    });
})(jqPopify);

1 个答案:

答案 0 :(得分:1)

在此处删除window.location.reload行:

$.fn.popifyClose = function(options) {
        var settings = $.extend(true,
            // No settings for popifyClse.
            {},
            // User supplied.
            options
        );

        $(this).trigger('fly-popify-hide');
        $('#flyPopifyOverlay , .flyPopifyOverlayContent, .closePopup').css({'z-index':-100,display:'none', opacity:0});
        // REMOVE THIS LINE
        // window.location.reload();
        return this;
    };

如果您在关闭弹出窗口时需要重新加载页面,这里有几个与重新加载时保持滚动位置相关的主题:

Refresh Page and Keep Scroll Position

keep scroll position after location.reload()