本文示範如何用 avalon.js 的雙向綁定做出「按住圖片拖曳、拖到哪裡就插到哪裡」的排序效果,就像微博、手機相簿那樣。整個實作的關鍵技巧是:拖曳過程中並不真的移動 DOM,而是把被拖的項目變成一個佔位符,讓資料陣列去反映新的順序,視圖自然就跟著更新。

<div id='post_img' ms-controller='post_img'>
<ul id='post_img_inner' ms-mousemove='onmousemove'>
<li ms-repeat-el="post_img_list" class='inline-block'
ms-mousedown='onmousedown($event,$index,el)'
ms-attr-id='post_img_item{{$index}}'>
<img ms-src='el' class='uploaded_img'></li>
</ul>
</div>
var drag_holder = null, index = -1, ori_src = null, drag_flag = false;
var post_img = avalon.define('post_img', function(vm) {
vm.post_img_list = []; // 保存所有圖片的 src
vm.onmousedown = function(e, i, el) {
$('drag_proxy').style.display = 'block';
var target = e.target.parentNode;
var xx = e.clientX, yy = e.clientY;
$('drag_proxy').style.top = yy + 'px';
$('drag_proxy').style.left = xx + 'px';
if (target && target.nodeName == 'LI') {
ori_src = el;
index = target.getAttribute('id').substring(13);
$('drag_proxy').innerHTML = target.innerHTML;
// 原位置先換成佔位圖
post_img.post_img_list.splice(i, 1, 'about:blank');
}
drag_flag = true;
};
vm.onmousemove = function(e) {
if (!drag_flag) return; // 沒按下就不處理
var xx = e.clientX, yy = e.clientY;
$('drag_proxy').style.top = yy + 'px';
$('drag_proxy').style.left = xx + 'px';
var x = xx - avalon($('post_img')).offset().left;
var y = yy - avalon($('post_img')).offset().top;
// 此例未考慮捲軸,實務上要加上 scrollTop 修正
var x_index = Math.floor(x / 100); // 圖片尺寸 100*100
var y_index = Math.floor(y / 100);
var target_index = 3 * y_index + x_index; // 3x3 的目標位置
post_img.post_img_list.splice(index, 1); // 移掉舊佔位符
if (post_img.post_img_list.indexOf('about:blank') != target_index)
post_img.post_img_list.splice(target_index, 0, 'about:blank');
index = target_index;
// mousemove 會觸發很多次,所以每次都更新一次位置
};
});
document.onmouseup = function(e) {
drag_holder = null;
if (ori_src) {
post_img.post_img_list.splice(index, 1); // 移掉佔位符
post_img.post_img_list.splice(index, 0, ori_src); // 放回真正的圖
}
$('drag_proxy').style.display = 'none';
$('drag_proxy').innerHTML = '';
drag_flag = false;
};
一般實作拖曳排序,直覺做法是直接搬 DOM 節點,但手動搬 DOM 又要處理事件綁定、索引對應,很容易出錯。這裡反其道而行:只改資料陣列,因為 avalon 的雙向綁定會自動把陣列變化反映到視圖上,DOM 交給框架處理就好。這正是 MVVM 相比直接操作 DOM 的價值所在。
範例中的 Math.floor(x / 100) 寫死了每格 100px,也假設固定 3 欄;一旦改成自適應寬度就會失效,實務上應該用實際容器寬度除以欄數來算格子大小。
另外,範例註解中已誠實說明「沒有考慮捲動條」,如果頁面可捲動,必須把 scrollTop/scrollLeft 加回座標計算,否則位置會偏。
最後,drag_proxy 這個浮動代理元素要在 HTML 中自行準備並設定 position:fixed,才能跟著游標跑。
如果你今天使用的是 Vue 或 React,同樣的思路仍然適用——拖曳只改資料狀態,rendering 交給框架;或直接使用 Sortable.js 這類成熟套件,能省下大量邊界處理的功夫。
以上就是 avalon 實作圖片拖曳排序的說明,希望對你的開發有所幫助。