表格类选中区域复制的实现

<html>
<head>
    <meta charset="UTF-8">
    <title>clipboard</title>
</head>
<body>
    <!-- 1 -->
    <!-- <p>点击复制后在右边textarea CTRL+V看一下</p>
    <input type="text" id="inputText" value="测试文本"/>
    <input type="button" id="btn" value="复制"/>
    <textarea rows="4"></textarea>
    <script type="text/javascript">
        var btn = document.getElementById('btn');
        btn.addEventListener('click', function(){
            var inputText = document.getElementById('inputText');
            var currentFocus = document.activeElement;
            inputText.focus();
            inputText.setSelectionRange(0, inputText.value.length);
            document.execCommand('copy', true);
            currentFocus.focus();
        });
    
    
    </script> -->
    

    <!-- 2 -->
    <style>
        .canvas { width: 520px; height: 300px; border: 1px solid #123; overflow: scroll;}
        .view { width: 520px; padding: 10px; }
        .view:after { content: ''; display: block; clear: both; }
        .row {}
        .cell {display: inline-block; width: 50px;border: 1px solid #456 }
        .selected { background-color: #aeeafb; }
    </style>
    <script src="../scroller/jquery.js"></script>
    <div class="canvas">
        <div class="view" tabindex="-1"></div>
    </div>
    <textarea id="selection" rows="4"></textarea>
    <script>
        var dataIndex = 'abcdefghij'.split('');
        var data = (function() {
            var items = [];
            var start = 0;

            for (let i = 0; i < 100; i++) {
                let item = {};
                for (let j = 0; j < 10; j++) {
                    item[dataIndex[j]] = start++;
                }
                items.push(item);
            }

            return items;
        })();

        var flag = false;
        var start, end, sec;

        $('.view')
            .append(function() {
                var rows = '';
                data.forEach((d, i) => {
                    let cells = '';
                    for (let key in d) {
                        cells += `<div class="cell" tabindex="-1" dataIndex="${key}">${d[key]}</div>`;
                    }
                    rows += `<div class="row" rid="${i}">${cells}</div>`;
                });

                return rows;
            })
            .on('mousedown', 'div.cell', function(evt) {
                $('.cell').removeClass('selected');
                flag = true;
                let $cell = $(this);
                start = [$cell.attr('dataIndex'), $cell.parent('.row').attr('rid')];
                // console.log(start);
            })
            .on('mouseenter', 'div.cell', function(evt) {
                if (flag) {
                    let $cell = $(this);
                    $cell.focus();
                    this.className = 'cell selected';
                    end = [$cell.attr('dataIndex'), $cell.parent('.row').attr('rid')];

                    selectionRange(start, end);
                }
            })
            .on('mouseup', function(evt) {
                flag = false;
                // console.log(end);
                console.log(sec);
                copy($('.cell.selected'));
            });
            

        function copy($cells) {
            var selection = document.getElementById('selection');
            selection.value = sec;
            
            var currentFocus = document.activeElement;
            selection.focus();
            selection.setSelectionRange(0, selection.value.length);
            document.execCommand('copy', true);
        }

        function swap(a, b) {
            return [b, a];
        }

        function orderBy(x0, y0, x1, y1) {
            if (dataIndex.indexOf(x0) > dataIndex.indexOf(x1)) {
                [x0, x1] = swap(x0, x1);
            }
            if (y0 > y1) {
                [y0, y1] = swap(+y0, +y1);
            }

            return [x0, y0, x1, y1];
        }

        var lastY;
        // start = ['a', 0], end = ['c', 3]
        // -> 0 ['a', 'b', 'c']
        // -> 1 ['a', 'b', 'c']
        // -> 2 ['a', 'b', 'c']
        // -> 3 ['a', 'b', 'c']
        function selectionRange([x0, y0], [x1, y1]) {
            let yDir = y1 - y0;
            
            // yRange = { last: , now: [y0, y1] };
            // [l0, l1]
            // [y0, y1]
            // [l0, l1]
            let removeYRange = [];
            // down
            if (yDir >= 0 && y1 < lastY) {
                removeYRange = [+y1, +lastY];
            }
            // up
            if (yDir <= 0 && y1 > lastY) {
                removeYRange = [+lastY, +y1];
            }
            
            lastY = y1;
            console.log(yDir, removeYRange);

            [x0, y0, x1, y1] = orderBy(x0, y0, x1, y1);

            let cols = dataIndex.slice(dataIndex.indexOf(x0), dataIndex.indexOf(x1)+1);
            let rows = data.slice(+y0, +y1 + 1);

            sec = rows.map(row => {
                return cols.map(col => row[col]);
            });


            $('.row').each((i, row) => {
                let $row = $(row);
                
                if (i >= +y0 && i < +y1 + 1) {
                    cols.forEach((col) => {
                        $row.find('div.cell').each((i, cell) => {
                            if (cols.indexOf(cell.getAttribute('dataIndex')) != -1) {
                                cell.className = 'cell selected';
                            } else {
                                cell.className = 'cell';
                            }
                        });
                    });
                }

                if (yDir >= 0 && i > removeYRange[0] && i <=removeYRange[1] ) {
                    $row.find('div.cell').removeClass('selected');
                }
                if (yDir <= 0 && i >= removeYRange[0] && i <removeYRange[1] ) {
                    $row.find('div.cell').removeClass('selected');
                }

            });
        }

    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/zhoulingfeng/p/8879469.html