如何使用JQuery将一个div元素定位在屏幕的实际中心位置?

7

我需要将一个div元素定位在屏幕中央。我找到了以下简单的代码,但我需要定位在实际屏幕中央而不是页面的“总高度/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;}

正如我所说,我需要计算实际屏幕尺寸(如1366*768或用户调整其浏览器的任何大小),并将元素放置在屏幕中央。 所以,如果我向下滚动页面,则始终应该将居中的div放置在中心位置。


这个答案可能会让你朝着正确的方向前进。这是一个相当古老的线程,所以我相信有一些很好的库可以包装不同浏览器所需的不同调用。 - Matt
@Matt 有一条评论说IE现在接受screenX和screenY了。所以现在它是跨浏览器兼容的。 :) - Pedro Estrada
3个回答

11

如果您可以使用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();
});

演示:http://jsfiddle.net/GoranMottram/D4BwA/1/


1

它有效..将其作为 #sample 来进行操作

给它的CSS样式为

#sample{
margin-left:auto;
margin-right:auto;
width:200px;//your wish
}

想一想,它起作用了...

如果你仔细阅读,这个问题是关于垂直居中的,而你提出的是水平居中。 - Havok

0

试试这个:

var width=$("#div").css("width");
var half=width/2;
$("#div").css("marginLeft","-"+half+"px");

用你的选择器替换 #div。


再说一遍...如果你仔细阅读,这个问题是关于垂直居中的,而你提出的是水平居中。 - Havok

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接