gpt4 book ai didi

jquery - 将 div 或对话框定位到窗口的中心

转载 作者:行者123 更新时间:2023-11-30 23:52:41 25 4
gpt4 key购买 nike

我使用以下代码将对话框定位到窗口的中心。

var dialog = $('#dialogBox');
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var dHeight = $('#dialogBox').height();
var dWidth = $('#dialogBox').width();
$('#dialogBox').css({top:windowHeight/2 - dHeight/2, left:windowWidth/2 - dWidth/2}).show();

它将 div 定位到窗口的中心。但我想将对话框定位到当前可见区域的中心。因此,即使我向下或向上滚动,对话框也将位于窗口的中心。如何用jquery做到这一点?

如有任何建议,我们将不胜感激!!!

谢谢。

最佳答案

你可以像这样使它居中:

$('#elementID').css({
position:'absolute',
top:'50%',
left:'50%',
width:'600px', // adjust width
height:'300px', // adjust height
zIndex:1000,
marginTop:'-150px' // half of height
marginLeft:'-300px' // half of width
});

请注意,元素将出现在中心,但滚动时它不会移动。如果你想让它显示在中心,你需要将position设置为fixed。然而,这在 IE6 中不起作用。所以决定权在你:)

<小时/>

您还可以创建快速简单的 jQuery 插件:

(function($){
$.fn.centerIt = function(settings){

var opts = $.extend({}, $.fn.centerIt.defaults, settings);

return this.each(function(settings){
var options = $.extend({}, opts, $(this).data());
var $this = $(this);

$this.css({
position:options.position,
top:'50%',
left:'50%',
width:options.width, // adjust width
height:options.height, // adjust height
zIndex:1000,
marginTop:parseInt((options.height / 2), 10) + 'px' // half of height
marginLeft:parseInt((options.width / 2), 10) + 'px' // half of height
});

});
}

// plugin defaults - added as a property on our plugin function
$.fn.centerIt.defaults = {
width: '600px',
height: '600px',
position:'absolute'
}

})(jQuery);

然后像这样使用它:

$('#elementId').centerIt({width:'400px', height:'200px'});

关于jquery - 将 div 或对话框定位到窗口的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5126958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com