使用 CSS 或 Javascript 复制/剪切时从文本中删除样式 [英] Remove Styles from Text when Copying / Cutting using CSS or Javascript

查看:32
本文介绍了使用 CSS 或 Javascript 复制/剪切时从文本中删除样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哟,

好吧,一直在研究这个:如何在不带任何样式包袱(背景颜色、颜色等)的情况下复制/剪切样式文本?

Alright been noodling on this one for a while: How copy/cut styled text without bringing along any style baggage (background-color, color, etc)?

已被挫败的几条攻击路线:

Couple of routes of attacks that have been foiled:

  1. 使用 ::select 为文本设置不同的样式? 不起作用, ::style 没有被复制
  2. 使用 jQuery 的选择绑定设置所选文本的样式 这仅适用于输入,而不适用于 p、div
  3. 通过使用 jQuery 将事件绑定到复制/粘贴来拦截和删除样式? 无法访问复制的对象以删除内容,尝试使用 e.preventDefault();然后返回事件对象,但这也不起作用
  4. 保存后修改剪贴板数据? 同样没有骰子,大多数浏览器不会让你在没有 Flash 和某种确认的情况下进入这个

无论如何,想法?似乎它对于具有白色背景颜色的网站非常有用.

Anyway, thoughts? Seems like it would be very useful for sites that have white background colors.

推荐答案

我现在没有时间编写示例,但是您可以为键盘快捷键触发的剪切/复制执行此操作.它不适用于通过上下文菜单或编辑菜单选项进行剪切/复制,因为它依赖于在剪切或复制事件触发之前更改用户选择.

I haven't got time to code up an example now, but you could do this for cut/copy triggered by keyboard shortcuts. It wouldn't work for cut/copy via context menu or Edit menu options because it relies on changing the user selection before the cut or copy event fires.

步骤:

  1. 处理 Ctrl-CCtrl-X 键盘快捷键和 Mac 等效项.
  2. 在此处理程序中,创建一个离屏元素(例如,绝对位置和左侧 -10000 像素)并将所选内容复制到其中.您可以使用 window.getSelection().getRangeAt(0).cloneContents() 来执行此操作,尽管您需要单独的 IE 代码 <9 并且您应该检查选择是否折叠.
  3. 随心所欲地更改屏幕外元素内容的样式.
  4. 移动选择以包含屏幕外元素的内容,以便剪切或复制此内容.
  5. 使用 window.setTimeout() 添加一个短暂的延迟(几毫秒),该延迟会调用一个删除屏幕外元素并恢复原始选择的函数.
  1. Handle the Ctrl-C and Ctrl-X keyboard shortcuts and the Mac equivalents.
  2. In this handler, create an off-screen element (absolute position and left -10000px, say) and copy the selected content into it. You can do this using window.getSelection().getRangeAt(0).cloneContents(), although you'll need separate code for IE < 9 and you should check the selection is not collapsed.
  3. Do whatever you like to to change the styling of the content of the off-screen element.
  4. Move the selection to encompass the content of the off-screen element so that it is this content that is cut or copied.
  5. Add a brief delay (a few milliseconds) using to window.setTimeout() that calls a function that removes the offscreen element and restores the original selection.

这篇关于使用 CSS 或 Javascript 复制/剪切时从文本中删除样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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