您的位置:首页 > 其它

div 拖拽改变容器宽度

2018-01-23 10:46 344 查看
左右排版的 div 容器,可以拖动改变 div 宽度的占比。



完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Resizable Div Container</title>
<meta name="description" content="可以对div进行拖动缩放大小">
<style type="text/css">
#container.resizable {
width: 100%;
height: 100%;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: moz-none;
-ms-user-select: none;
user-select: none;
position: relative;
opacity: 0;
}
#container.resizable #left {
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 85%;
overflow: hidden;
background-color: #ccc;
}
#container.resizable #right {
position: absolute;
right: 0px;
top: 0px;
bottom: 0px;
width: 85%;
background: #fff;
padding-left: 4px;
overflow: hidden;
background-color: #ddd;
}
#container.resizable #resizor {
position: absolute;
top: 50%;
right: 85%;
cursor: w-resize;
background-color: #666;
border-radius: 5px;
margin-top: -10px;
width: 6px;
height: 20px;
/*background: url('/public/static/admin/images/resize.png') repeat-y;*/
background-size: cover;
background-position: center;
z-index: 99999;
}
</style>
</head>
<body>
<div id="container" class="resizable">
<!-- Left side -->
<div id="left">
<p>左侧内容</p>
</div>
<div id="resizor" title="拖动我"></div>
<!-- Right side -->
<div id="right">
<p>右侧内容</p>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
var isResizing = false;
var lastDownX = 0;

$(function () {
var container = $('#container.resizable');
// 根据当前窗口大小设定 container 的高度
container.css({'height': ($(window).height() - 20), 'opacity': 1});

var left = $('#left');
var right = $('#right');
var resizor = $('#resizor');

resizor.on('mousedown', function (e) {
isResizing = true;
lastDownX = e.clientX;
});

$(document).on('mousemove', function (e) {
if (!isResizing) return true;
var offsetRight = container.width() - (e.clientX - container.offset().left);
// 判断左右拖动范围
if (offsetRight < 0 || offsetRight >= container.width()) {
isResizing = false;
return true;
}
left.css('right', offsetRight);
resizor.css('right', offsetRight);
right.css('width', offsetRight);
}).on('mouseup', function (e) {
isResizing = false;
});
});
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  div resize