jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery – 将div或对话框定位到窗口的中心大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码将对话框定位到窗口的中心.

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
});

请注意,元素将出现在中心但滚动时不会移动.如果要使其显示在中心,则需要将位置设置为固定.但是,这在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,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或对话框定位到窗口的中心全部内容,希望文章能够帮你解决jquery – 将div或对话框定位到窗口的中心所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。