天天看點

擷取光标的位置,并在光标位置插入内容。

擷取光标的位置,并在光标位置插入内容。
擷取光标的位置,并在光标位置插入内容。

應用場景一般都是這種編輯器的比較多。

下面的例子是這樣的。

如果我先在input框裡輸入幾個日日日,然後在中間點了一下。最後把添加的内容寫在第二個框裡。點選添加。

你在第二個框裡輸入的内容就插到你剛才點的光标的位置啦。

擷取光标的位置,并在光标位置插入内容。

但是他有個問題就是如果我想輸入的是個公式什麼的有html标簽的元素。那麼他也會把标簽帶過去。

但是我們真正想要的樣式是希望它能解析出來标簽的。

擷取光标的位置,并在光标位置插入内容。
擷取光标的位置,并在光标位置插入内容。

我試了一下把這個input換成可以編輯的div,這樣<div contenteditable="true"  id='txt1' ></div>。然後下面本來是擷取value的地方都換成innerHTML。

這樣也是輸入框的效果。但是發現根本沒有添加進去如何内容。

最後我隻能說,好像這個隻能在input裡面才能擷取到selectionStart這些屬性才知道你的光标在哪裡。

這個也隻适用于輸入的内容不能帶任何的樣式。

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>無标題文檔</title>

</head>

<body>

<input name="" id="txt1" cols="30" rows="10"   :placeholder= /><br>

<input type="text" name="" id="txt2">

<input type="button" value="添加" id="btn">

<input type="button" value="擷取内容" id="btn1" οnclick="get()">

<div id="thistext"></div>

<script type="text/javascript">

window.onload = function(){

    var oTxt1 = document.getElementById("txt1");

    var oTxt2 = document.getElementById("txt2");

    var oBtn = document.getElementById("btn");

    oBtn.onclick = function(){

    getValue("txt1", oTxt2.value);

    }

}

</script>

<script type="text/javascript">

    function get(){

        document.getElementById("thistext").innerHTML=document.getElementById("txt1").value;

        console.log(document.getElementById("txt1").value)

    }

//了在IE、Firefox、Opera等主流浏覽器的擷取光标位置(getCursortPosition)以及設定光标位置(setCursorPosition)的函數    

//objid:textarea的id   str:要插入的内容

function getValue(objid,str){

   var myField=document.getElementById(""+objid);

   //IE浏覽器

     if (document.selection) {

       myField.focus();

       sel = document.selection.createRange();

       sel.text = str;

       sel.select();

     }

     //火狐/網景 浏覽器

     else if (myField.selectionStart || myField.selectionStart == '0')

     {

     //得到光标前的位置

       var startPos = myField.selectionStart;

       //得到光标後的位置

       var endPos = myField.selectionEnd;

       // 在加入資料之前獲得滾動條的高度

       var restoreTop = myField.scrollTop;

       myField.value = myField.value.substring(0, startPos) + str + myField.value.substring(endPos, myField.value.length);

       //如果滾動條高度大于0

       if (restoreTop > 0) {

         // 傳回

         myField.scrollTop = restoreTop;

       }

       myField.focus();

       myField.selectionStart = startPos + str.length;

       myField.selectionEnd = startPos + str.length;

     }

     else {

       myField.value += str;

       myField.focus();

     }

   }

</script>

</body>

</html>

可以看另一篇。如何在div是contentEditable=true的裡面擷取焦點的位置,并在焦點處插入内容。

https://blog.csdn.net/qq_33769914/article/details/93596502