简体   繁体   English

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

[英]Restrict paste in contenteditable (HTML / JS)

I would like to prevent the user from pasting non allowed markup in a contenteditable div. 我想阻止用户在一个contenteditable div中粘贴不允许的标记。

I would like to restrict paste to bold, italic, strike, underline and links. 我想将粘贴限制为粗体,斜体,打击,下划线和链接。

What is the best way (I'm using jQuery ) ? 什么是最好的方式(我使用jQuery )?

This is not a duplicate of JQuery Text Editor Paste Without Formatting . 这不是JQuery Text Editor Paste Without Formatting的重复。 I don't want to paste without formatting. 我不想在没有格式化的情况下粘贴。 I want to select / restrict to some markups. 我想选择/限制一些标记。

I already read the following questions, none provides a clear answer: 我已经阅读了以下问题,没有提供明确答案:

Restrict pasted content by listening to the editable element's paste event. 通过侦听可编辑元素的paste事件来限制粘贴的内容。 Inside this event, you can filter the data the user is attempting to paste by using a regular expression. 在此事件中,您可以使用正则表达式过滤用户尝试粘贴的数据。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM