Div Resize方法

当一个<div>需要实现resize时,除了使用jQuery UI 的resizable插件,也可以自己编写JS实现,这时
就需要用到js的mousedown,mousemove,mouseup事件,源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>draw</title>
<script src="js/jquery-1.11.0.min.js"></script>
<style>
#drawBorder{
width:600px;
height:2px;
background: deeppink;
cursor: n-resize;
margin:-10px auto 0 auto;
border-bottom:10px solid transparent ;
border-top:10px solid transparent;
-webkit-background-clip: padding-box;
-moz-background-clip: padding-box;
background-clip: padding-box;
}
#content{
width:600px;
height:300px;
margin:0 auto;
border:1px solid deeppink;
}
</style>
</head>
<body>
<div id="content"></div>
<div id="drawBorder"></div>
<script>
$("#drawBorder").mousedown(function () {
var mouseDownY=$(this).offset().top; //鼠标点击下边缘时,下边缘距离窗口顶端的高度。
var contentHeight=$("#content").height();
$(document).mousemove(function (e) {
var currentHeight=contentHeight+e.clientY-mouseDownY; //e.clientY为鼠标移动时Y轴坐标,currentHeight为当前高度
$("#content").height(currentHeight+"px"); //重置高度
});
});
$(document).mouseup(function(){
$(document).unbind("mousemove"); //鼠标弹起时,解除`movemove`事件的监听
});
</script>
</body>
</html>