gpt4 book ai didi

javascript - 限制在 contenteditable 中粘贴 (HTML/JS)

转载 作者:太空狗 更新时间:2023-10-29 14:17:08 25 4
gpt4 key购买 nike

我想阻止用户在 contenteditable div 中粘贴不允许的标记。

我想将粘贴限制为粗体、斜体、删除线、下划线和链接。

最好的方法是什么(我正在使用 jQuery)?

这不是 JQuery Text Editor Paste Without Formatting 的副本. 我不想在没有格式化的情况下粘贴。我想选择/限制某些标记。

我已经阅读了以下问题,没有一个提供明确的答案:

最佳答案

通过监听可编辑元素的 paste 事件来限制粘贴的内容。在此事件中,您可以使用正则表达式过滤用户尝试粘贴的数据。

const el = document.querySelector('p');

el.addEventListener('paste', (e) => {
// Get user's pasted data
let data = e.clipboardData.getData('text/html') ||
e.clipboardData.getData('text/plain');

// Filter out everything except simple text and allowable HTML elements
let regex = /<(?!(\/\s*)?(a|b|i|em|s|strong|u)[>,\s])([^>])*>/g;
data = data.replace(regex, '');

// Insert the filtered content
document.execCommand('insertHTML', false, data);

// Prevent the standard paste behavior
e.preventDefault();
});
<p contenteditable>Try pasting content into this paragraph. The pasted content can include a <b>BOLD</b>, <i>ITALIC</i>, <s>STRIKE</s>, or <u>UNDERLINE</u>. It can also include a <a href='#'>LINK</a>.</p>

关于javascript - 限制在 contenteditable 中粘贴 (HTML/JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53186433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com