改变大小
要求:鼠标放到小div上点击改变大小,离开小div后点击则不再改变。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
padding: 0;
margin: 0;
border: 0;
}
#big{
width: 200px;
height: 200px;
background-color: antiquewhite;
position: relative;
}
#small{
width: 50px;
height: 50px;
background-color: rgb(3, 3, 3);
position: absolute;
right: 0;
bottom: 0;
}
#small:hover{
/* 使鼠标变成双箭头形式 */
cursor: nw-resize;
}
img{
width: 100%;
height:100%;
}
</style>
<body>
<div id="big" >
<div id="small">
</div>
</div>
<script>
let smallDom=document.querySelector('#small')
smallDom.onmousedown=function(event){
let xDiff=event.offsetX;
let yDiff=event.offsetY;
//鼠标点击位置到smalldiv左边和下边的距离
let rigth=smallDom.clientWidth-xDiff;
let bottom=smallDom.clientHeight-yDiff;
let bigdiv=document.querySelector('#big')
//offsetLeft,offsetTop,与带有定位的父元素最左边和最上边之间的偏移量
document.onmousemove=function(event){
bigdiv.style.width=event.clientX-bigdiv.offsetLeft+rigth+'px'
bigdiv.style.height=event.clientY-bigdiv.offsetTop+bottom+'px'
}
}
document.onmouseup=function(){
document.onmousemove=null;
}
</script>
</body>
</html>
拖拽
要求:鼠标按下div跟着鼠标移动,鼠标弹起div在鼠标弹起地位置随即停止移动。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div{
height: 80px;
width: 80px;
background-color: darksalmon;
margin: auto;
position: absolute;
}
</style>
<body>
<div>
</div>
<script>
let div=document.querySelector('div')
//鼠标按下
div.onmousedown=function(event1){
//鼠标移动
let X=event1.offsetX;
let Y=event1.offsetY;
document.onmousemove=function(event){
div.style.left=event.clientX-X+'px'
div.style.top=event.clientY-Y+'px'
}
//鼠标弹起
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
</script>
</body>
</html>