在html/mvc中实现对表列的拖放操作



我有一个基于数据库结果生成表的网站。我希望用户有能力移动表(这是嵌套在单元格)周围重新排序。我在这里找到了一篇很接近的文章。所以我试着摆弄了一把小提琴,但我不能很好地工作。下面是JavaScript:

    var dragSrcEl = null;
function handleDragStart(e) {
    this.style.opacity = '0.4';
    dragSrcEl = this;
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
}
function HandleDragOver(e) {
    if (e.preventDefault) {
        e.preventDefault();
    }

    e.dataTransfer.dropEffect = 'move';
    return false;
}
function handleDragEnter(e) {
    this.classList.Add('over');
}
function handleDragLeave(e) {
    this.classList.remove('over');
}
function handleDrop(e) {
    // this/e.target is current target element.
    if (e.stopPropagation) {
        e.stopPropagation(); // Stops some browsers from redirecting.
    }
    // Don't do anything if dropping the same column we're dragging.
    if (dragSrcEl != this) {
        // Set the source column's HTML to the HTML of the column we dropped on.
        dragSrcEl.innerHTML = this.innerHTML;
        this.innerHTML = e.dataTransfer.getData('text/html');
    }
    return false;
}
function handleDragEnd(e) {

    [].forEach.call(cols, function (col) {
        col.classList.remove('over');
    });
}
var cols = document.querySelectorAll('td.DashPad');
[].forEach.call(cols, function (col) {
    col.addEventListener('dragstart', handleDragStart, false);
    col.addEventListener('dragenter', handleDragEnter, false);
    col.addEventListener('dragover', handleDragOver, false);
    col.addEventListener('dragleave', handleDragLeave, false);
    col.addEventListener('drop', handleDrop, false);
    col.addEventListener('dragend', handleDragEnd, false);
});

它在移动时改变第一个表的不透明度,但其他的都不改变。而且它根本不做拖放操作。是否有可能做我想做的与持有表格的表格单元格?

我推荐使用jQuery。有一种排序方法可以很容易地处理这个任务。我所做的就是将class="sortable"添加到外部表中,并将所有javascript替换为以下内容:

$('.sortable').sortable({items: '.DashPad'});

这是JSFiddle的工作副本http://jsfiddle.net/d1s5ur48/3/

更多关于jQuery的排序:https://jqueryui.com/sortable/

最新更新