table td拖拽单元格内容交换

  拖动单元格到其他单元格上,2个单元格内容相互交换,源代码如下

<script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
<style>
td.hover{border:dotted 3px #f00 }
td.selected{background:#f00;color:#fff;}
td.disabled{background:#eee;color:#000}
#tdMove{position:absolute;display:none;border:dotted 3px #f00;background:#fff}
table{user-select:none;-moz-user-select:none}</style>
<table border="1">
    <script>
        var s = ''
        for (var i = 0; i < 10; i++) {
            s += '<tr>'
            for (var j = 0; j < 10; j++) s += '<td' + (Math.random() > 0.8 ? ' class="disabled"' : '') + '>' + i + '-' + j + '</td>'
            s += '</tr>'
        }
        document.write(s)
    </script>
</table>
<div id="tdMove"></div>
<script>
    var tdMove = $('#tdMove'),px=5;//浮动块偏移量,不偏移鼠标移动过程会出现在这个div移动的情况,移动到td上无法响应高亮样式
    $('td:not(.disabled)').mousedown(function (e) {
        this.className = 'selected'
        tdMove.html(this.innerHTML).css({ left: e.clientX + px, top: e.clientY + px }).show();;
        $(document).mousemove(function (e) {
            var el = e.target;
            tdMove.css({ left: e.clientX + px, top: e.clientY + px });
            if (el.tagName == 'TD' && el.className != 'disabled' && el.className != 'selected') {
                $('td').removeClass('hover'); el.className = 'hover';
            }
        }).mouseup(function () {
            $(document).unbind();

            tdMove.hide();
            var td = $('td.hover,td.selected')
            if (td.length == 2) {
                var s = td[1].innerHTML;
                td[1].innerHTML = td[0].innerHTML;
                td[0].innerHTML = s;
            }
            td.removeClass('hover selected')
        });
    })
</script>

 


原创文章,转载请注明出处:table td拖拽单元格内容交换

评论(0)Web开发网
阅读(274)喜欢(0)JavaScript/Ajax开发技巧