微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将div元素定位在ACTUAL屏幕的中心? (JQuery的)

我需要将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;}

正如我所说,我需要计算实际的屏幕尺寸(如1366 * 768或任何用户调整其浏览器的大小)并将元素定位在屏幕的中心.所以,如果我向下滚动页面,总是居中的div应该再次位于中心.

解决方法

如果您使用固定定位而不是绝对定位,则可以使用以下内容
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/

原文地址:https://www.jb51.cc/css/215382.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。