JQuery Modal居中的效果對(duì)于頁(yè)面美觀和用戶體驗(yàn)都有很大的提升。下面我們來(lái)介紹幾種實(shí)現(xiàn)方法。
代碼示例1: $(document).ready(function(){ $('#modal1').css('display', 'block'); //modal居中 var modalHeight = $('#modal1').outerHeight(); var modalWidth = $('#modal1').outerWidth(); $('#modal1').css({ 'margin-left': -modalWidth/2 + 'px' 'margin-top': -modalHeight/2 + 'px' }); }); 代碼示例2: $(document).ready(function(){ $('#modal2').css('display', 'block'); //modal居中 var modalHeight = $('#modal2').outerHeight(); var modalWidth = $('#modal2').outerWidth(); $(window).resize(function(){ var winHeight = $(window).height(); var winWidth = $(window).width(); var modalLeft = (winWidth - modalWidth) / 2; var modalTop = (winHeight - modalHeight) / 2; $('#modal2').css({ 'left': modalLeft + 'px', 'top': modalTop + 'px' }); }); }); 代碼示例3: $(document).ready(function(){ $('#modal3').css('display', 'block'); //modal居中 $('#modal3').center(); $(window).resize(function(){ $('#modal3').center(); }); }); $.fn.center = function(){ this.css('position', 'fixed'); this.css('top', ($(window).height() - this.outerHeight())/2+'px'); this.css('left', ($(window).width() - this.outerWidth())/2+'px'); return this; };
在實(shí)際開(kāi)發(fā)中,選擇合適的方法能夠大幅減少頁(yè)面編寫(xiě)的代碼量和提高用戶體驗(yàn)。希望大家都能寫(xiě)出美觀和實(shí)用的網(wǎng)頁(yè)。