jquery左右拖动改变div宽度

直接看代码吧

<html>
	<head>
		<title>拖动调整左右两侧div的宽度</title>
		<style>
			#container {
				display: flex;
				height: 400px;
				width: 100%;
			}

			#left,
			#right {
				/* flex: 1; */
				width: 50%;
			}

			#left {
				background-color: #ff0000;
			}

			#right {
				background-color: #00ff00;
			}

			#handle {
				position: absolute;
				top: 0;
				width: 5px;
				height: 100%;
				background-color: #0000ff;
				cursor: col-resize;
			}
		</style>
	</head>
	<body>
		<div id="container">
			<div id="left"></div>
			<div id="right"></div>
		</div>
	</body>
	<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
	<script>
		$(document).ready(function() {
			var container = $("#container");
			var left = $("#left");
			var right = $("#right");
			var handle = $("<div id='handle'></div>");
			var width = $(window).width();
			// 添加拖动句柄
			container.append(handle);

			// 设置拖动句柄的初始位置
			handle.css("left", left.outerWidth());

			// 绑定拖动事件
			handle.on("mousedown", function(e) {
				e.preventDefault();
				console.log("research=== 111")

				// 记录鼠标初始位置和左侧div的宽度
				var startX = e.pageX;
				var initialLeftWidth = left.outerWidth();

				// 绑定鼠标移动事件
				$(document).on("mousemove", function(e) {
					e.preventDefault();
					// 计算鼠标移动距离
					var moveX = e.pageX - startX;
					console.log("mousemove width:", width)
					console.log("mousemove left:", left)
					console.log("mousemove moveX:", moveX)
					console.log("mousemove initialLeftWidth:", initialLeftWidth)
					// 更新左侧div和拖动句柄的宽度
					left.width(initialLeftWidth + moveX);
					right.width(width-initialLeftWidth- moveX);
					left.css('width', initialLeftWidth + moveX)
					handle.css("left", left.outerWidth());
				});

				// 绑定鼠标释放事件
				$(document).on("mouseup", function() {
					$(document).off("mousemove");
					$(document).off("mouseup");
				});
			});
		});
	</script>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值