jquery实现元素自适应水平垂直居中

jquery实现元素居中插件:
(function($){
    $.fn.vhAlign =  function(){
        return this.each(function(i){
            //获取元素的内容高度
            var h = Math.ceil($(this).height());
            //outerHeight=padding+border+height
            var oh = Math.ceil($(this).outerHeight());
            //取得margin-top值
            var mt = Math.ceil(oh / 2);
            //取得元素宽度
            var w = Math.ceil($(this).width());
            //outerWidth=padding+border+width
            var ow = Math.ceil($(this).outerWidth());
            //取得margin-left
            var ml = Math.ceil(ow / 2);
            //实现元素居中效果
            $(this).css({
                "margin-top": "-" + mt + "px",
                "top": "50%",
                "margin-left": "-" + ml + "px",
                "left": "50%",
                "width":w,
                "height":h,
                "position": "absolute"
            }); 
        });
    };
})(jQuery);
常用demo:
$(window).resize(function(){ 
    $(".mydiv").css({ 
        position: "absolute", 
        left: ($(window).width() - $(".mydiv").outerWidth())/2, 
        top: ($(window).height() - $(".mydiv").outerHeight())/2 
    });        
}); 
此外在页面载入时,就需要调用resize()。
 
$(function(){ 
    $(window).resize(); 
});
 
jQuery方法实现图片居中插件:
$.fn.imgVAlign=function(){
return $(this).each(function(i){
//获取图片的src值,并定义给变量bg
var bg = $(this).attr("src");
//给图片的父元素定义背景图片的样式,并且背景图片
$(this).parent().css({"background": "url("+ bg +") no-repeat center center"
});
//将图片隐藏
$(this).css("opacity","0");
});
}
//调用上面写的插件
$(document).ready(function(){
$(".imgBox img").imgVAlign();
});
 
posted @ 2015-04-12 17:53  前端丶守望者  阅读(2161)  评论(0编辑  收藏  举报