js 改变盒子大小
知识点
三个 mouse 事件: mousedown mousemove mouseup
CSS 的定位和 cursor
思路
先解决单边问题
识别范围, 得到所选区域 event.
根据距离, 判断方向
根据方向进行样式的增加减少, 注意 top 和 left 的变化
当然还要增加最小的限制
注意
识别改变的四个位置
得到它们的范围
判断改变范围的大小
注意改变 top 和 left 的边的时候, 注意将盒子的 left 变为 this.offsetLeft-(原来的 event.clientX 减去现在的 event.clinentX);top 则变为 this.offsetTop-(原来的 event.clientY 减去现在的 event.clinentY)
最后还要限制最小的范围
- var container=document.getElementById(container),
- span=document.getElementById(span),
- move=document.getElementById(move),
- wrap=document.getElementById(wrap)
- divs=container.getElementsByTagName(div),
- top=divs[0],
- bottom=divs[1],
- left=divs[2],
- right=divs[3];
- // 找到位置
- container.onmousedown=function(event){
- var event=event||window.event
- event.preventDefault()
- var mouseDownX=event.clientX
- var mouseDownY=event.clientY
- // 得到位置
- var topLocal=this.offsetTop
- var bottomLocal=this.offsetTop+this.offsetHeight
- var leftLocal=this.offsetLeft
- var rightLocal=this.offsetLeft+this.offsetWidth
- var w=this.offsetWidth
- var h=this.offsetHeight
- // 识别范围
- var areaT=topLocal+20
- var areaB=bottomLocal-20
- var areaL=leftLocal+20
- var areaR=rightLocal-20
- // 判断改变方块的大小方向
- var changeL=event.clientX<areaL
- var changeR=event.clientX>areaR
- var changeT=event.clientY<areaT
- var changeB=event.clientY>areaB
- document.onmousemove=function(event){
- var event=event||window.event
- if(changeL){
- container.style.left=leftLocal-(mouseDownX-event.clientX)+px
- container.style.width=(mouseDownX-event.clientX)+w+px
- }
- if(changeR){
- container.style.width=event.clientX-mouseDownX+w+px
- }
- if(changeT){
- container.style.top=topLocal-(mouseDownY-event.clientY)+px
- container.style.height=mouseDownY-event.clientY+h+px
- }
- if(changeB){
- container.style.height=event.clientY-mouseDownY+h+px
- }
- if(parseInt(container.style.width)<150){
- container.style.width=150+px
- document.onmousemove=null
- }
- if(parseInt(container.style.height)<150){
- container.style.height=150+px
- document.onmousemove=null
- }
- }
- document.onmouseup=function(){
- document.onmousemove=null
- document.onmouseup=null
- }
- }
来源: http://www.bubuko.com/infodetail-2529319.html