JS實(shí)現(xiàn)在文本指定位置插入內(nèi)容的簡單示例
更新時(shí)間:2017年12月22日 09:28:47 作者:Bazinga_fine
下面小編就為大家分享一篇JS實(shí)現(xiàn)在文本指定位置插入內(nèi)容的簡單示例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
實(shí)例如下所示:
function insertAtCursor(myField, myValue) {
//IE 瀏覽器
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
//FireFox、Chrome等
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) + myValue + myField.value.substring(endPos, myField.value.length);
if (restoreTop > 0) {
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
myField.focus();
}
}
<textarea id="textarea" style="width: 386px; height: 260px">
</textarea>
<input type="text" id="text" />
<input type="button" value="插入" onclick="insertAtCursor(document.getElementById('textarea'),document.getElementById('text').value)" />
以上這篇JS實(shí)現(xiàn)在文本指定位置插入內(nèi)容的簡單示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
JS中setInterval、setTimeout不能傳遞帶參數(shù)的函數(shù)的解決方案
在JS中無論是setTimeout還是setInterval,在使用函數(shù)名作為調(diào)用句柄時(shí)都不能帶參數(shù),而在許多場合必須要帶參數(shù),接下來為大家介紹具體的解決方法2013-04-04
js中位數(shù)不足自動補(bǔ)位擴(kuò)展padLeft、padRight實(shí)現(xiàn)代碼
這篇文章主要介紹了js中位數(shù)不足自動補(bǔ)位擴(kuò)展之padLeft、padRight實(shí)現(xiàn)方法,主要是通過String.prototype擴(kuò)展實(shí)現(xiàn),需要的朋友可以參考下2020-04-04
深入理解javascript動態(tài)插入技術(shù)
這篇文章介紹了javascript動態(tài)插入技術(shù),有需要的朋友可以參考一下2013-11-11
webpack4手動搭建Vue開發(fā)環(huán)境實(shí)現(xiàn)todoList項(xiàng)目的方法
這篇文章主要介紹了webpack4手動搭建Vue開發(fā)環(huán)境實(shí)現(xiàn)todoList項(xiàng)目的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05
js對象實(shí)例詳解(JavaScript對象深度剖析,深度理解js對象)
下面小編就為大家?guī)硪黄猨s對象實(shí)例詳解(JavaScript對象深度剖析,深度理解js對象)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09

