我正在使用 SharePoint 页面和脚本编辑器构建一个复制按钮,用于快速复制/粘贴 SharePoint 上使用的模板。我当前使用的代码工作完美,只是它不会复制以进行格式化。
对于此特定代码的上下文,我按照以下步骤来构建它。
使用下面的 JavaScript 代码,我希望复制功能能够复制 SharePoint 字段中文本的格式。
公平警告:我对JavaScript一无所知。有人能够为我构建这段代码,但除了我在这里显示的内容之外,我只知道一些代码如何工作。我不知道从哪里开始排除故障,并且当我研究其他编码时,我不知道从哪里开始对此代码添加修改。如果我需要帮助,请提前表示歉意。
我的印象是,最多只有一两行代码,我可以添加到现有代码中,以便它保持文本大小、粗体、下划线、超链接等格式。
如有任何帮助,我们将不胜感激。
function myFunction(divId) {
const copyDiv = document.getElementById(divId);
if (copyDiv) {
const textToCopy = copyDiv.innerText;
navigator.clipboard.writeText(textToCopy)
.then(() => {
let tooltip = document.getElementById("myTooltip");
tooltip.innerHTML = "Copied";
setInterval(() => {
tooltip.innerHTML = "Copy Template"
}, 1000);
})
.catch(err => {
console.error('Could not copy text: ', err);
});
} else {
console.error('Element to copy from could not be found');
}
}
<div>
<button onclick="myFunction('2ed477e2-32d7-4f46-a4a9-0a55cdba22f5')" onmouseout="outFunc()">
<span class="tooltiptext" id="myTooltip">Copy Template</span>
</button>
</div>
<div class="ControlZone ControlZone--clean a_b_50a7110f" data-automation-id="CanvasControl" id="2ed477e2-32d7-4f46-a4a9-0a55cdba22f5">
<div class="ControlZone--control">
<div data-sp-feature-tag="Rich Text Editor" class="rte-webpart rte--ck5 rte--read-ck5 headerFontSizeLegacy" data-sp-feature-instance-id="2ed477e2-32d7-4f46-a4a9-0a55cdba22f5" dir="auto">
<div data-automation-id="textBox" class="ck-content rteEmphasis root-161 rte-deprecated-styles">
<div>
<h2 id="bigger-text">Bigger Text<span class="c_b_1310c973"></span></h2>
<a class="c_b_1310c973 e_b_1310c973 focusBorder-147" role="link" aria-label="Permalink for Bigger Text" data-sp-anchor-id="bigger-text" href="https://garmin.sharepoint.com/sites/PSSharedSupport-PSCommunityTeam/Architect-Wiki/SitePages/Test-Page.aspx#bigger-text"
target="_self" style="left: 140px; top: 118px;"><i class="f_b_1310c973 g_b_1310c973 css-146" aria-hidden="true"></i></a>
</div>
<p>This is the text field from which the copy button is copied. As of now, it will not copy over formatting like <strong>bold</strong>, <i>italicized</i>, and <u>underlined</u> text formatting.</p>
</div>
</div>
</div>
</div>
p
的文本。const myFunction = (divId) => {
const copyDiv = document.getElementById(divId);
if (copyDiv) {
const elementToCopy = copyDiv.querySelector('p'); // otherwise we will copy the whole div
navigator.clipboard.write([new ClipboardItem({
'text/plain': new Blob([elementToCopy.innerText], {type: 'text/plain'}),
'text/html': new Blob([elementToCopy.innerHTML], {type: 'text/html'})
})])
.then(() => {
let tooltip = document.getElementById("myTooltip");
tooltip.innerHTML = "Copied";
setInterval(() => {
tooltip.innerHTML = "Copy Template"
}, 1000);
})
.catch(err => {
console.error('Could not copy text: ', err);
});
} else {
console.error('Element to copy from could not be found');
}
}