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

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.οnlοad=function() {
    autosize($(".na_popup"));
}
window.οnresize=function() {
    autosize($(".na_popup"));
}


你可能感兴趣的:(jQuery,javascript)