【问题标题】:is it possible to copy html to clipboard for hidden element?是否可以将 html 复制到剪贴板以获取隐藏元素?
【发布时间】:2021-12-06 11:23:57
【问题描述】:

我有一个部分,我希望用户将 html 复制到剪贴板,这个元素应该隐藏在这里是我目前所拥有的

现场演示:live demo

这是我到目前为止的代码。

export default function App() {
  const tableRef = useRef(null);
  const textRef = useRef(null);
  const [copySuccess, setCopySuccess] = useState("");

  const copyToClipboard = (e) => {
    let tableRange = document.createRange();
    tableRange.selectNodeContents(tableRef.current);
    let sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(tableRange);
    document.execCommand("Copy");
    sel.removeAllRanges();
    setCopySuccess("Copied!");
  };

  return (
    <div className="App">
      <textarea
        ref={textRef}
        style={{ opacity: 0, position: "absolute", top: "-200px" }}
      ></textarea>
      <div
        aria-hidden="true"
        ref={tableRef}
        className="table"
        style={{ display: "none" }}
      >
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Username</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>1</td>
              <td>Mark</td>
              <td>Otto</td>
              <td>@mdo</td>
            </tr>
          </tbody>
        </table>
      </div>

      {document.queryCommandSupported("copy") && (
        <div>
          <button onClick={copyToClipboard}>Copy</button>
          {copySuccess}
        </div>
      )}
    </div>
  );
}

预期:将隐藏的 html 表格复制到剪贴板

我需要做什么才能将该隐藏元素复制到剪贴板?

【问题讨论】:

  • 好的,你要复制哪一部分? textarea? div? table?
  • @hisam 桌子

标签: javascript reactjs html-table react-hooks use-ref


【解决方案1】:

好的,隐藏元素不能直接在 DOM 中使用,因此您不能从那里复制它。它们仅用于将数据从一种状态传输到另一种状态,或从渲染表单传输回控制器。如果您需要该数据,可以将其绑定到 ViewBag 中。

const a = window.param;

window.param = ViewBag.param;

const copyToClipboard = (e) => {
ViewBag.param = e;
    let tableRange = document.createRange();
    tableRange.selectNodeContents(tableRef.current);
    let sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(tableRange);
    document.execCommand("Copy");
    sel.removeAllRanges();
    setCopySuccess("Copied!");
  };

也请参考此链接。 Access a viewbag property in reactjs

【讨论】:

  • 老兄 ASP.NET MVC 中的 ViewBag
猜你喜欢
  • 1970-01-01
  • 2015-03-07
  • 2017-01-11
  • 2023-02-09
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
相关资源
最近更新 更多