在javascript中从剪贴板获取html [英] Get html from clipboard in javascript

查看:955
本文介绍了在javascript中从剪贴板获取html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现RichTextEditors非常常见的任务 - 从剪贴板中获取 HTML
任何人都可以帮助指导如何解决这个任务吗?

I need to implement task which is quite common feature for RichTextEditors - take HTML from clipboard. Can anyone help with guide on how to solve this task?

它必须是跨平台的(IE,FF,Chrome,Opera)。
我刚从这段代码开始:

It has to be cross platform (IE, FF, Chrome, Opera). I just started from this code:

<script type="text/javascript">
    $('.historyText').live('input paste', function(e) {

        var paste = e.clipboardData && e.clipboardData.getData ?
        e.clipboardData.getData('text/plain') :                // Standard
        window.clipboardData && window.clipboardData.getData ?
        window.clipboardData.getData('Text') :                 // MS
        false;

        alert(paste);
    });</script>

window.clipboardData和e.clipboardData都为空(Chrome,Firefox)。

Both window.clipboardData and e.clipboardData are null (Chrome, Firefox).

更新:用户想要粘贴其他浏览器窗口中的文章内容,我需要获取html标签。

Update: User wants to paste article content from other browser windows, and I need to get html tags.

推荐答案

您将无法单独使用JavaScript从剪贴板获取数据,这是应该的方式。当前版本的TinyMCE和CKEditor执行此操作的方式如下:

You won't be able to get data from the clipboard using JavaScript alone, which is the way it should be. The way current versions of TinyMCE and CKEditor do this is as follows:


  1. 使用按键事件检测ctrl-v / shift-ins事件处理程序

  2. 在该处理程序中,保存当前用户选择,在屏幕外添加div元素(例如在左边-1000px处)到文档,将插入符移动到该div内部,从而有效地重定向粘贴

  3. 在事件处理程序中设置一个非常简短的计时器(比如1毫秒)来调用另一个从div中检索HTML内容的函数,并执行任何所需的处理,删除文档中的div,恢复用户选择并插入已处理的HTML。

请注意,这仅适用于键盘粘贴事件而不是来自上下文或编辑菜单的粘贴。当粘贴事件触发时,将插入符重定向到div中已经太晚了(至少在某些浏览器中)。

Note that this will only work for keyboard paste events and not pastes from the context or edit menus. By the time the paste event fires, it's too late to redirect the caret into the div (in some browsers, at least).

这篇关于在javascript中从剪贴板获取html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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