Sai*_*aya 7 html jquery center
我需要将div元素放在屏幕的中心.我在下面找到了一个简单的代码,但我需要ACTUAL屏幕的中心,而不是页面的"总高度/ 2"!
这里是Jquery代码,它以元素为中心,但不是实际的屏幕;
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;}
Run Code Online (Sandbox Code Playgroud)
正如我所说,我需要计算实际的屏幕尺寸(如1366*768或任何用户调整其浏览器大小)并将元素定位在屏幕的中心.所以,如果我向下滚动页面,总是居中的div应该再次位于中心.
Gor*_*ram 10
如果您使用fixed定位而不是absolute,则可以使用以下内容:
jQuery.fn.center = function ()
{
this.css("position","fixed");
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
$('#myDiv').center();
$(window).resize(function(){
$('#myDiv').center();
});
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/GoranMottram/D4BwA/1/
| 归档时间: |
|
| 查看次数: |
22325 次 |
| 最近记录: |