微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

表格在 cookie 中保存列位置

如何解决表格在 cookie 中保存列位置

我有以下代码 - 来自 this 站点的纯 JavaScript 拖放表项并从 this 站点设置 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>

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

谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。