這次帶給大家JS用拖曳事件改變物體大小,JS用拖曳事件改變物體大小的注意事項有哪些,下面就是實戰案例,一起來看一下。
拖曳改變物件大小功能:拖曳黃色小p來改變綠色大p的寬和高
#
主要實作由三大步:
#
1. 透過id取得到大小兩個p
2. 給小p加上onmousedown事件
3. 在onmousedown事件給document新增onmousemove和onmouseup事件
#
由分析圖可知,我們只需要在拖曳的時候,取得到物體不斷增加的寬度值,問題就解決了
1 2 3 | <p id= "panel" >
<p id= "dragIcon" ></p>
</p>
|
登入後複製
加些樣式
1 2 3 4 5 6 7 8 9 10 11 12 | <style>
#panel{
position: absolute;
width: 200px;height: 200px;
background: green;
}
#dragIcon{
position: absolute;bottom: 0;right: 0;
width: 20px;height: 20px;
background: yellow;
}
</style>
|
登入後複製
js實作程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <script>
window.onload = function () {
var oPanel = document.getElementById( 'panel' );
var oDragIcon = document.getElementById( 'dragIcon' );
var disX = 0;
var disY = 0;
var disW = 0;
var disH = 0;
oDragIcon.onmousedown = function (ev) {
var ev = ev || window.event;
disX = ev.clientX;
disY = ev.clientY;
disW = oPanel.offsetWidth;
disH = oPanel.offsetHeight;
document.onmousemove = function (ev) {
var ev = ev || window.event;
var W = ev.clientX - disX + disW;
var H = ev.clientY - disY + disH;
if (W<100){
W = 100;
}
if (W>800){
W =800;
}
if (H<100){
H = 100;
}
if (H>500){
H = 500;
}
oPanel.style.width =W + 'px' ;
oPanel.style.height = H + 'px' ;
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
</script>
|
登入後複製
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
vue.js實現無縫捲動效果的步奏詳解
實作react伺服器渲染的步奏詳解
#
以上是JS用拖曳事件改變物體大小的詳細內容。更多資訊請關注PHP中文網其他相關文章!