js改變盒子大小(上下左右)分析
阿新 • • 發佈:2018-03-16
nts 知識點 ont elements move bottom left color eal
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 } }
js改變盒子大小(上下左右)分析