简体   繁体   中英

Resize modal from center using JavaScript and CSS

I have the following fiddle example: http://jsfiddle.net/c2mmQ/

Where I show a modal using jQuery when I click the show link, and fade it in and scale it up using CSS animations. Inside the modal I have another link which resizes the modal. The idea is that it should resize from the middle so it looks like it's scaling up (although we are NOT using scale as we are actually changing the dimensions of modal). Think how the popups work on an Xbox 360.

Two issues happen.. first while the resizing does honour the css transitions, they don't fire the event transitionend so the center code doesn't run after the resize. And the second issue is that the resizing doesn't happen from the center...

Any ideas on how I can do this?

Code is below:

jQuery.fn.centerImage = function () {

    var win = window.parent;

    var element = $(this);

    var centerElement = function () {
        element.css("position", "absolute");
        element.css("top", ( (($(win).height()) - element.outerHeight()) / 2));
        element.css("left", ( (($(win).width()) - element.outerWidth()) / 2));
    }

    element.bind('centerElement', centerElement).trigger('centerElement');

    $($(win)).bind('resize', function () {
        element.trigger('centerElement');
    });

    return element;
}

$(document).ready(function(){

    $('.show').on('click', function(e){

        $('.modal').centerImage().addClass('show');

    });

    $('.resize').on('click', function(e){

        $('.modal').width(640).height(480);

        $('modal').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
            $('.modal').centerImage();
        });

    });

});

.modal
{
    width: 480px;
    height: 320px;
    background: #ffffff;
    box-shadow: rgba(0,0,0,.6) 0 0 16px;

    -webkit-transform: scale(0.7);
    -moz-transform: scale(0.7);
    -ms-transform: scale(0.7);
    transform: scale(0.7);
    opacity: 0;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    transition: all 0.3s;
}

.modal.show
{
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    opacity: 1;
}

You're going to kick yourself!

$('modal').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
            $('.modal').centerImage();
        });

should be

$('.modal').on('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
            $('.modal').centerImage();
        });

http://jsfiddle.net/robschmuecker/c2mmQ/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM