【问题标题】:Highlight html table cell onclick and copy value with CTRL + C使用 CTRL + C 突出显示 html 表格单元格 onclick 并复制值
【发布时间】:2014-01-01 18:40:36
【问题描述】:

我找到了一个很好的脚本来突出显示 html 表格行,它工作正常:

http://nerds-central.blogspot.ca/2006/12/selectable-table-rows-with-html-and.html

我将 onclick 事件更改为 onmouseover,并添加了几行来选择一个单元格 onclick。所以,我可以选择它,检查哪个被选中并获取值,但我想在按下 CTRL + C 时复制单元格值而无需选择内容(如在 Microsoft Excel 中)。

只需 CTRL + C 应该没问题,但是如果您也有线索可以使用右键单击下拉菜单来解决问题,那就太棒了!

【问题讨论】:

  • 请参阅:stackoverflow.com/questions/400212/… 完全跨浏览器兼容的解决方案需要 Flash,因为大多数浏览器都可以轻松访问计算机的剪贴板。
  • 你能提供一个小提琴,以便我们有一些工作吗?

标签: javascript html html-table cell


【解决方案1】:

这是一个 sn-p,它会在复制之前自动选择一个单元格,尽管它仅适用于 CTRL+C

window.onload = function () {
    var selected,
        selectCell = function (e) {
            var cell = e.target,
                range, selection;
            if (cell.tagName.toLowerCase() !== 'td') {
                while (cell = cell.parentElement) {
                    if (cell.tagName.toLowerCase() === 'td') {
                        break;
                    }               
                }
            }
            if (!cell || cell.tagName.toLowerCase() !== 'td') {
                return;
            }
            if (selected) {
                selected.style.backgroundColor = '';            
            }
            cell.style.backgroundColor = '#ff0';
            selected = cell;
        },
        beforeCopyCell = function (e) {
            var range, selection;
            if (!selected || !e.ctrlKey || e.which !== 67) {
                return;
            }
            selected.focus();
            selection = window.getSelection();
            selection.removeAllRanges();
            range = document.createRange();
            range.selectNode(selected);             
            selection.addRange(range);
        },
        afterCopyCell = function (e) {
            if (!selected || !e.ctrlKey || e.which !== 67) {
                return;
            }
            selection = window.getSelection();
            selection.removeAllRanges();
        },
        table = document.getElementById('table');
    table.addEventListener('click', selectCell);
    table.addEventListener('keydown', beforeCopyCell);
    document.body.addEventListener('keyup', afterCopyCell);
};

代码似乎在 FF25、Chrome31 和 IE11 中运行良好,但在 IE

A live demo at jsFiddle。 (小提琴演示了一个替代代码,它不适用于 IE。)

Another demo,它还以某种方式实现了通过上下文菜单复制单元格。这仅适用于 FF26、Chrome31 和 IE11,但如果省略/重建所选单元格的类切换,则代码应该是 IE9+ 可战斗的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2016-08-07
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
相关资源
最近更新 更多