在contenteditable中限制粘贴(HTML / JS) [英] Restrict paste in contenteditable (HTML / JS)

查看:773
本文介绍了在contenteditable中限制粘贴(HTML / JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to prevent the user from pasting non allowed markup in a contenteditable div.

我会喜欢将粘贴限制为粗体,斜体,敲击,下划线和链接。

I would like to restrict paste to bold, italic, strike, underline and links.

最好的方法是什么(我使用 jQuery

What is the best way (I'm using jQuery) ?

这不是 JQuery文本编辑器粘贴而不格式化我不想在没有格式化的情况下粘贴。我想选择/限制一些标记。

This is not a duplicate of 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:

  • JQuery Text Editor Paste Without Formatting
  • How to filter user pasted content in contenteditable div?
  • Javascript trick for 'paste as plain text` in execCommand
  • Contenteditable allowing only plain text

推荐答案

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

Restrict pasted content by listening to the editable element's paste event. 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>

这篇关于在contenteditable中限制粘贴(HTML / JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆