`
rguess
  • 浏览: 69666 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类

jquery实现居中可拖拽窗体

    博客分类:
  • web
阅读更多
<html>
	<head>
		<script src="jquery-1.8.3.min.js" type="text/javascript"></script>
		
		<script>
			(function ($) {
			  /**
			   * 居中
			   */
			  $.fn.center = function (settings) {
				var style = $.extend({
				  position: 'absolute', //absolute or fixed
				  top     : '50%', //50%即居中,将应用负边距计算,溢出不予考虑了。
				  left    : '50%',
				  zIndex  : 2009,
				  relative: true //相对于包含它的容器居中还是整个页面
				}, settings || {});

				return this.each(function () {
				  var $this = $(this);

				  if (style.top == '50%') style.marginTop = -$this.outerHeight() / 2;
				  if (style.left == '50%') style.marginLeft = -$this.outerWidth() / 2;
				  if (style.relative && !$this.parent().is('body') && $this.parent().css('position') == 'static') $this.parent().css('position', 'relative');
				  delete style.relative;
				  //ie6
				  if (style.position == 'fixed' && $.browser.version == '6.0') {
					style.marginTop += $(window).scrollTop();
					style.position = 'absolute';
					$(window).scroll(function () {
					  $this.stop().animate({
						marginTop: $(window).scrollTop() - $this.outerHeight() / 2
					  });
					});
				  }
				  $this.css(style);
				});
			  };
			  
			  /**
			   * 可移动
			   */
			  $.fn.move = function (obj) {
				  
				  var $win = obj;
				  var $title = $(this);
				  
				  var b = false;
				  var x;
				  var y;
				  $title.css("cursor", "move");
				  $title.mousedown(
					function (e) {
						//x,y坐标是点击事件点和外该组件的距离差
						b = true;
						x = e.pageX - parseInt($win.position().left);
						y = e.pageY - parseInt($win.position().top);
					});
				  $(document).mousemove(
					  function (e) {
						  //只要不释放鼠标就可以拖动div
						  if (b) {
							  var divleft = e.pageX - x;
							  var divtop = e.pageY - y;
							  //设置拖动左,上位置
							  $win.css({ "left": divleft, "top": divtop });
						  }
					  }
					).mouseup(function () {
						b = false;
					});
			  };  
			})(jQuery);
		</script>
		
		<script>
			$(function(){
				$(".div").center();
				$(".title").move($(".div"));
			});
		</script>
		
		<style>
			.div{width:400px;height:300px;border:1px solid #F00}
			.title{
				width : 400px;
				height : 30px;
				background-color : green;
				cursor : move;
				margin-top : -1px;
			}
		</style>
	</head>
	<body>
		<div class="div">
			<h3 class="title">鼠标放到上边</h3>
		</div>
	</body>
</html>
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics