您的位置:首页 > Web前端 > JQuery

jQuery实现DIV屏幕自动水平垂直居中

2017-12-09 14:49 573 查看
css

.na_popup{ width:900px; height:150px; position: fixed; z-index: 1500; top:0; left: 0; }
//封装jQuery插件版

(function($) {
var methods = {
autosize: function(ele) {
if(ele.height() <= $(window).height()) {
ele.css("top", ($(window).height() - ele.height()) / 2);
}
if(ele.width() <= $(window).width()) {
ele.css("left", ($(window).width() - ele.width()) / 2);
}
}
}
$.fn.extend({
propup: function(options) {
$this = $(this);
methods.autosize($this);

$(window).resize(function() {
methods.autosize($this);
});
}
});
})(jQuery);

$(".na_popup").propup();//要居中的DOM元素


//js版(window.onload,window.onresize时执行)

function autosize(ele) {
    if($(".na_popup").height() <= $(window).height()) {
        ele.css("top", ($(window).height() - ele.height()) / 2);
    }
    if(ele.width() <= $(window).width()) {
        ele.css("left", ($(window).width() - ele.width()) / 2);
    }
}
window.onload=function() {
    autosize($(".na_popup"));
}
window.onresize=function() {
    autosize($(".na_popup"));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: