<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现拖拽缩放元素</title>
<style>
#div1 {
width: 11px;
height: 11px;
background-color: #000;
position: absolute;
bottom: 0;
right: 0;
cursor: nw-resize;
}
#div2 {
width: 200px;
height: 150px;
background: #CCC;
position: relative;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
oDiv.onmousedown = function (ev) {
var oEvent = ev || event;
var disX = oEvent.clientX - oDiv.offsetLeft;
var disY = oEvent.clientY - oDiv.offsetTop;
document.onmousemove = function (ev) {
var oEvent = ev || event;
//要加上子DIV的大小(oDiv.offsetWidth与oDiv.offsetHeight)
oDiv2.style.width = oEvent.clientX - disX + oDiv.offsetWidth + 'px';
oDiv2.style.height = oEvent.clientY - disY + oDiv.offsetHeight + 'px';
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</head>
<body>
<div id="div2">
<div id="div1"></div>
</div>
</body>
</html>
网友评论