jquery统计出来
代码如下 | 复制代码 |
if($("#cont1").css("position")!="fixed"){ $("#cont1").css("position","absolute"); var dw = $(window).width(); var ow = $("#cont1").outerWidth(); var dh = $(window).height(); var oh = $("#cont1").outerHeight(); var l = (dw - ow) / 2; var t = (dh - oh) / 2 > 0 ? (dh - oh) / 2 : 10; var lDiff = $("#cont1").offset().left - $("#cont1").position().left; var tDiff = $("#cont1").offset().top - $("#cont1").position().top; l = l + $(window).scrollLeft() - lDiff; t = t + $(window).scrollTop() - tDiff; $("#cont1").css("left",l + "px"); $("#cont1").css("top",t + "px"); } |
jquery+css 实现居中
通过css创建一个水平居中和垂直居中的div是一件比较麻烦的事情,您必须事先知道另外一个div的尺寸:
代码如下 | 复制代码 |
.className{ width:300px; height:200px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -150px; } |
通过jQuery实现水平居中和垂直居中前面已经提到过了,css的方法只适用于有固定尺寸的div,所以到jQuery发挥作用了:
代码如下 | 复制代码 |
$(window).resize(function(){ $('.className').css({ position:'absolute', left: ($(window).width() - $('.className').outerWidth())/2, top: ($(window).height() - $('.className').outerHeight())/2 + $(document).scrollTop() }); }); //初始化函数 $(window).resize(); 此外在页面载入时,就需要调用resize()。 $(function(){ |
此方法的好处就是不需要知道DIV的具体宽度和高度大小,直接用jQuery就可以实现水平和垂直居中,而且兼容各浏览器,这个方法在很多的弹出层效果中应用。
通过css实现水平居中和垂直居中
例子
代码如下 | 复制代码 |
<body> <div class="pos"> <div class="boxA">测试用的内内容测测试用的内容</div> </div> </body> *{ margin:0; padding:0;} |
总结:外层的定位:需要是自适应宽度的;(float:left 或者 position:absolute;)
内层的位定:需要是自动100%宽度的(相对于外层100%);
时间: 2024-08-01 22:07:14