简体   繁体   English

在光标位置插入HTML,然后使用javascript将光标移动到插入的html的末尾

[英]Inserting HTML at cursors position and moving cursor to end of inserted html with javascript

I am writing a script to insert presaved html content into Gmail's editable iframe in the compose page mentioned below. 我正在编写一个脚本,用于在下面提到的撰写页面中将保存的html内容插入Gmail的可编辑iframe中。 This script is only to be used in Greasemonkey on Firefox. 该脚本仅在Firefox的Greasemonkey中使用。 So I don't need to consider any other browser. 因此,我不需要考虑任何其他浏览器。

Currently it inserts the text once and then gets bugged. 目前,它只插入一次文本,然后被窃听。 I guess because range.setStart() expects first parameter is a node, which createContextualFragment() does not return. 我猜是因为range.setStart()期望第一个参数是一个节点,而createContextualFragment()不会返回。

Is there any other way to add html at current cursor's position and then move cursor to the end of the added html (not to the end of all content)? 还有其他方法可以在当前光标的位置添加html,然后将光标移至添加的html的末尾(而不是所有内容的末尾)?

https://mail.google.com/mail/?view=cm&fs=1&tf=1&source=mailto&to=example@example.com https://mail.google.com/mail/?view=cm&fs=1&tf=1&source=mailto&to=example@example.com

function insertTextAtCursor(text) {
    var sel, range, html, textNode;
    if (window.frames[3].window.frames[0].getSelection()) {
        sel = window.frames[3].window.frames[0].getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            textNode = range.createContextualFragment(text);
            //textNode = document.createTextNode(text);
            range.insertNode( textNode );
            range.setStart(textNode, textNode.length);
            range.setEnd(textNode, textNode.length);
            sel.removeAllRanges();
            sel.addRange(range);
            window.frames[3].window.frames[0].focus();
        }
    }
}

Update 1: If i comment the code to move the cursor after inserting html then its no longer bugged, but the cursor stays in the same place. 更新1:如果我注释了插入html后移动光标的代码,则它不再出错,但光标停留在同一位置。

//range.setStart(textNode, textNode.length);
//range.setEnd(textNode, textNode.length);
sel.removeAllRanges();
//sel.addRange(range);

got you something. 给你点东西。

with the help from this answer , i wrote this: 这个答案的帮助下,我这样写道:

  1. paste your text/html at the cursor position 将您的text / html粘贴到光标位置
  2. move the cursor to the end of the text area 将光标移到文本区域的末尾

save this as test.html to test it locally 将其另存为test.html以在本地进行测试

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    jQuery.fn.extend({
        insertAtCaret: function(myValue){
          return this.each(function(i) {
            if (document.selection) {
              //For browsers like Internet Explorer
              this.focus();
              sel = document.selection.createRange();
              sel.text = myValue;
              this.focus();
            }
            else if (this.selectionStart || this.selectionStart == '0') {
              //For browsers like Firefox and Webkit based
              var startPos = this.selectionStart;
              var endPos = this.selectionEnd;
              var scrollTop = this.scrollTop;
              this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
              this.focus();
              this.selectionStart = startPos + myValue.length;
              this.selectionEnd = startPos + myValue.length;
              this.scrollTop = scrollTop;
            } 
            else {
              this.value += myValue;
              this.focus();
            }
          })
        }
    });

    var myhtml = '<b> this html will be <i>added</i> to the </b> cursor position (and will move to the end)';
    var movetotheendof = '';
    $(window).load(function(){
        $('#btnpastepre').click(function() {
            $('#txtarea').insertAtCaret(myhtml)
            movetotheendof = $('#txtarea').val()
            $('#txtarea').val("").val(movetotheendof)
        })
    });
    </script>
</head>

<body>

    <div id="formcontainer">
        <button id="btnpastepre">click to paste</button>

        <form id="formulario">
            <textarea id="txtarea" cols=60 rows=20></textarea>
        </form>
    </div>

</body>

</html>

or click here to test it online: http://jsfiddle.net/RASG/Vwwm4/ 或单击此处在线进行测试: http : //jsfiddle.net/RASG/Vwwm4/

Now all you have to do is change it according to your needs (gmail or any other site) 现在您所要做的就是根据您的需要进行更改(gmail或任何其他网站)

EDIT 编辑

I forgot that you wanted a GM script :) 我忘了你想要一个通用脚本:)
Here it is 这里是

// ==UserScript==
// @name        TESTE 3
// @namespace   TESTE 3
// @description TESTE 3
// @require     http://code.jquery.com/jquery.min.js
// @include     *
// @version     1
// ==/UserScript==


jQuery.fn.extend({
    insertAtCaret: function(myValue){
        return this.each(function(i) {
            if (document.selection) {
                //For browsers like Internet Explorer
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            }
            else if (this.selectionStart || this.selectionStart == '0') {
                //For browsers like Firefox and Webkit based
                var startPos = this.selectionStart;
                var endPos = this.selectionEnd;
                var scrollTop = this.scrollTop;
                this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
                this.focus();
                this.selectionStart = startPos + myValue.length;
                this.selectionEnd = startPos + myValue.length;
                this.scrollTop = scrollTop;
            } 
            else {
                this.value += myValue;
                this.focus();
            }
        })
    }
});

var myhtml = '<b> this html will be <i>added</i> to the </b> cursor position (and will move to the end)';
var movetotheendof = '';

$(window).load(function(){
    $('#btnpastepre').click(function() {
        $('#txtarea').insertAtCaret(myhtml)
        movetotheendof = $('#txtarea').val()
        $('#txtarea').val("").val(movetotheendof)
    })
})

Just create an html file with this content to test it 只需创建具有此内容的html文件即可对其进行测试

<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <div id="formcontainer">
        <button id="btnpastepre">click to paste</button>
        <form id="formulario">
            <textarea id="txtarea" cols=60 rows=20></textarea>
        </form>
    </div>
</body>
</html>

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

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