<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body, html {
width: 100%;
height: 100%;
margin: 0;
}
#container {
width: 200px;
height: 200px;
padding: 15px;
border: #00cdcd 2px solid;
box-sizing: border-box;
}
.item {
cursor: default;
width: 100%;
height: 100%;
background: #757575;
}
</style>
</head>
<body id="body">
<div id="container">
<div class="item"></div>
</div>
<script>
//需要调整尺寸的div
let c = document.getElementById('container')
// body监听移动事件
document.getElementById('body').addEventListener('mousemove', move)
// 鼠标按下事件
c.addEventListener('mousedown', down)
// 鼠标松开事件
document.getElementById('body').addEventListener('mouseup', up)
// 是否开启尺寸修改
let resizeable = false
// 鼠标按下时的坐标,并在修改尺寸时保存上一个鼠标的位置
let clientX, clientY
// div可修改的最小宽高
let minW = 8, minH = 8
// 鼠标按下时的位置,使用n、s、w、e表示
let direc = ''
// 鼠标松开时结束尺寸修改
function up() {
resizeable = false
}
// 鼠标按下时开启尺寸修改
function down(e) {
let d = getDirection(e)
// 当位置为四个边和四个角时才开启尺寸修改
if (d !== '') {
resizeable = true
direc = d
clientX = e.clientX
clientY = e.clientY
}
}
// 鼠标移动事件
function move(e) {
let d = getDirection(e)
let cursor
if (d === '') cursor = 'default';
else cursor = d + '-resize';
// 修改鼠标显示效果
c.style.cursor = cursor;
// 当开启尺寸修改时,鼠标移动会修改div尺寸
if (resizeable) {
// 鼠标按下的位置在右边,修改宽度
if (direc.indexOf('e') !== -1) {
c.style.width = Math.max(minW, c.offsetWidth + (e.clientX - clientX)) + 'px'
clientX = e.clientX
}
// 鼠标按下的位置在上部,修改高度
if (direc.indexOf('n') !== -1) {
c.style.height = Math.max(minH, c.offsetHeight + (clientY - e.clientY)) + 'px'
clientY = e.clientY
}
// 鼠标按下的位置在底部,修改高度
if (direc.indexOf('s') !== -1) {
c.style.height = Math.max(minH, c.offsetHeight + (e.clientY - clientY)) + 'px'
clientY = e.clientY
}
// 鼠标按下的位置在左边,修改宽度
if (direc.indexOf('w') !== -1) {
c.style.width = Math.max(minW, c.offsetWidth + (clientX - e.clientX)) + 'px'
clientX = e.clientX
}
}
}
// 获取鼠标所在div的位置
function getDirection(ev) {
let xP, yP, offset, dir;
dir = '';
xP = ev.offsetX;
yP = ev.offsetY;
offset = 10;
if (yP < offset) dir += 'n';
else if (yP > c.offsetHeight - offset) dir += 's';
if (xP < offset) dir += 'w';
else if (xP > c.offsetWidth - offset) dir += 'e';
return dir;
}
</script>
</body>
</html>