0

我有以下代码 - 来自该站点的纯 javascript 拖放表项并从此站点设置 cookie 。

问题:我想在拖放时保存位置列window.onload

如何将列列表位置保存在 cookie 中的表格中?

小提琴:https ://jsfiddle.net/e712xv4j/

谁能建议我的代码?

const table = document.getElementById('table');

let draggingEle;
let draggingColumnIndex;
let placeholder;
let list;
let isDraggingStarted = false;

let x = 0;
let y = 0;

const swap = function(nodeA, nodeB) {
    const parentA = nodeA.parentNode;
    const siblingA = nodeA.nextSibling === nodeB ? nodeA : nodeA.nextSibling;

    nodeB.parentNode.insertBefore(nodeA, nodeB);

    parentA.insertBefore(nodeB, siblingA);
};

const isOnLeft = function(nodeA, nodeB) {
    const rectA = nodeA.getBoundingClientRect();
    const rectB = nodeB.getBoundingClientRect();

    return (rectA.left + rectA.width / 2 < rectB.left + rectB.width / 2);
};

const cloneTable = function() {
    const rect = table.getBoundingClientRect();

    list = document.createElement('div');
    list.classList.add('clone-list');
    list.style.position = 'absolute';
    list.style.left = `${rect.left}px`;
    list.style.top = `${rect.top}px`;
    table.parentNode.insertBefore(list, table);

    table.style.visibility = 'hidden';

    const originalCells = [].slice.call(table.querySelectorAll('tbody td'));

    const originalHeaderCells = [].slice.call(table.querySelectorAll('th'));
    const numColumns = originalHeaderCells.length;

    originalHeaderCells.forEach(function(headerCell, headerIndex) {
        const width = parseInt(window.getComputedStyle(headerCell).width);

        const item = document.createElement('div');
        item.classList.add('draggable');

        const newTable = document.createElement('table');
        newTable.setAttribute('class', 'clone-table');
        newTable.style.width = `${width}px`;

        // Header
        const th = headerCell.cloneNode(true);
        let newRow = document.createElement('tr');
        newRow.appendChild(th);
        newTable.appendChild(newRow);

        const cells = originalCells.filter(function(c, idx) {
            return (idx - headerIndex) % numColumns === 0;
        });
        cells.forEach(function(cell) {
            const newCell = cell.cloneNode(true);
            newCell.style.width = `${width}px`;
            newRow = document.createElement('tr');
            newRow.appendChild(newCell);
            newTable.appendChild(newRow);
        });

        item.appendChild(newTable);
        list.appendChild(item);
    });
};

const mouseDownHandler = function(e) {
    draggingColumnIndex = [].slice.call(table.querySelectorAll('th')).indexOf(e.target);

    x = e.clientX - e.target.offsetLeft;
    y = e.clientY - e.target.offsetTop;

    document.addEventListener('mousemove', mouseMoveHandler);
    document.addEventListener('mouseup', mouseUpHandler);
};

const mouseMoveHandler = function(e) {
    if (!isDraggingStarted) {
        isDraggingStarted = true;

        cloneTable();

        draggingEle = [].slice.call(list.children)[draggingColumnIndex];
        draggingEle.classList.add('dragging');

        placeholder = document.createElement('div');
        placeholder.classList.add('placeholder');
        draggingEle.parentNode.insertBefore(placeholder, draggingEle.nextSibling);
        placeholder.style.width = `${draggingEle.offsetWidth}px`;
    }

    draggingEle.style.position = 'absolute';
    draggingEle.style.top = `${draggingEle.offsetTop + e.clientY - y}px`;
    draggingEle.style.left = `${draggingEle.offsetLeft + e.clientX - x}px`;

    x = e.clientX;
    y = e.clientY;

    const prevEle = draggingEle.previousElementSibling;
    const nextEle = placeholder.nextElementSibling;

    if (prevEle && isOnLeft(draggingEle, prevEle)) {
        swap(placeholder, draggingEle);
        swap(placeholder, prevEle);
        return;
    }

    if (nextEle && isOnLeft(nextEle, draggingEle)) {
        swap(nextEle, placeholder);
        swap(nextEle, draggingEle);
    }
};

const mouseUpHandler = function() {
    placeholder && placeholder.parentNode.removeChild(placeholder);

    draggingEle.classList.remove('dragging');
    draggingEle.style.removeProperty('top');
    draggingEle.style.removeProperty('left');
    draggingEle.style.removeProperty('position');

    const endColumnIndex = [].slice.call(list.children).indexOf(draggingEle);

    isDraggingStarted = false;

    list.parentNode.removeChild(list);

    table.querySelectorAll('tr').forEach(function(row) {
        const cells = [].slice.call(row.querySelectorAll('th, td'));
        draggingColumnIndex > endColumnIndex
            ? cells[endColumnIndex].parentNode.insertBefore(cells[draggingColumnIndex], cells[endColumnIndex])
            : cells[endColumnIndex].parentNode.insertBefore(cells[draggingColumnIndex], cells[endColumnIndex].nextSibling);

        //  createCookie('tablecell',cells)
    });


    table.style.removeProperty('visibility');

    document.removeEventListener('mousemove', mouseMoveHandler);
    document.removeEventListener('mouseup', mouseUpHandler);
};

table.querySelectorAll('th').forEach(function(headerCell) {
    headerCell.classList.add('draggable');
    headerCell.addEventListener('mousedown', mouseDownHandler);
})

// ===================================== Cookie =======================================


function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

window.onload= () => {

    //  readCookie('tablecell')
  
}
   .table th, .table td {
        border: 1px solid #ccc;
    }
    .table th, .table td {
        padding: 0.5rem;
    }
    .draggable {
        cursor: move;
        user-select: none;
    }
    .placeholder {
        background-color: #edf2f7;
        border: 2px dashed #cbd5e0;
    }
    .clone-list {
        border-left: 1px solid #ccc;
        border-top: 1px solid #ccc;
        display: flex;
    }
    .clone-table {
        border-collapse: collapse;
        border: none;
    }
    .clone-table th, .clone-table td {
        border: 1px solid #ccc;
        border-left: none;
        border-top: none;
        padding: 0.5rem;
    }
    .dragging {
        background: #fff;
        border-left: 1px solid #ccc;
        border-top: 1px solid #ccc;
        z-index: 999;
    }
<table class="table" id="table">
  <tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

对不起我的英语不好,我试着解释我需要的一切,希望你能理解我的需要。

谢谢!

4

0 回答 0