使用背景:
測試layui的多圖片上傳中,發現了一個問題。就是說當多圖片上傳后順序無法進行更改,在不修改layui的框架前提下這里有兩種方案:1,按照上傳時間排序,2用js可以滑塊進行拖拽修改。
都不難,這里就簡單記錄一下,話不多說,開擼!(ps:貌似同步上傳可以避免這種問題,沒有具體研究。)
c#按順序獲取文件夾中的文件
上傳則不變,只需要將獲取文件的方法重寫一下。代碼如圖:
public class FileComparer : IComparer { /// <summary> /// 文件排序 /// </summary> /// <param name="o1"></param> /// <param name="o2"></param> /// <returns></returns> int IComparer.Compare(object o1, object o2) { FileInfo fi1 = o1 as FileInfo; FileInfo fi2 = o2 as FileInfo; return fi1.CreationTime.CompareTo(fi2.CreationTime); } }
public static FileInfo[] GetFilesList(string path) { var di = new DirectoryInfo(path);//文件夾所在目錄 var fc = new FileComparer(); FileInfo[] fileList = di.GetFiles(); Array.Sort(fileList, fc);//按文件創建時間排正序 return fileList; }
目前是按照時間排序,可更改為大小,類型,等具體看需求。
js滑塊的運用
此方式,是利用了文件名稱排序的規則,則利用拖拽修改順序后,進行重新命名。所使用的ui框架是:https://jqueryui.com/sortable/#display-grid,效果如下:



代碼也很簡單直接源代碼就可以運行。
<!DOCTYPE>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖拽排序</title>
<style>
.sortable-ghost {
opacity: 0.4;
background-color: #F4E2C9;
}
.block__list li {
cursor: pointer;
}
</style>
</head>
<!-- <link href="app.css" rel="stylesheet" type="text/css"/>
-->
<!-- script src="./Sortable.js"></script> -->
<script src="https://cdn.bootcss.com/Sortable/1.8.3/Sortable.js"></script>
<body>
<button id="btn">關閉拖拽</button>
<ul id="foo" class="block__list block__list_words">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>
<script>
var sortable = new Sortable(document.getElementById('foo'), {
animation: 150, //動畫參數
disabled: false,//開關狀態
onAdd: function (evt) { //拖拽時候添加有新的節點的時候發生該事件
console.log('onAdd.foo:', [evt.item, evt.from]);
},
onUpdate: function (evt) { //拖拽更新節點位置發生該事件
console.log('onUpdate.foo:', [evt.item, evt.from]);
},
onRemove: function (evt) { //刪除拖拽節點的時候促發該事件
console.log('onRemove.foo:', [evt.item, evt.from]);
},
onStart: function (evt) { //開始拖拽出發該函數
console.log('onStart.foo:', [evt.item, evt.from]);
},
onSort: function (evt) { //發生排序發生該事件
console.log('onSort.foo:', [evt.item, evt.from]);
},
onEnd: function (evt) { //拖拽完畢之后發生該事件
console.log('onEnd.foo:', [evt.item, evt.from]);
}
});
var btn = document.getElementById('btn')
btn.onclick = function () {
console.log('123')
console.log(sortable)
var state = sortable.option("disabled"); // get
console.log(state)
sortable.option("disabled", !state); // set
}
</script>
</body>
</html>
