css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <p>文本框:</p>
<textarea name="" id="textarea" cols="30" rows="10">
sASASADASDasfaDFDsfsDFAfdFADf
</textarea>
<button type="button" id="setSelectText">选中特定范围的文本</button>
<button type="button" id="insertAfterText">在光标后插入文本</button>
<br>
<hr>
<br>
<input type="number" name="" id="input">
<button type="button" id="setCurPosBtn">设置光标位置</button>
<br>
<hr>
<br>
<p id="selectText">我是一段可以选中的文字,请打开控制台查看。我是一段可以选中的文字,请打开控制台查看。我是一段可以选中的文字,请打开控制台查看。</p>
            
          
!
            
              /**
* 光标位置组件
* ## selectRange对象的方法:
*   (1)selectRange.of(ele)   [创建光标位置获取的新对象]
           参数:
                ele  {{JavaScript DOM}}  光标所在的元素,原生JavaScript DOM

*   (2)selectRange.getCurPos()   [获取当前坐标位置]

*   (3)selectRange.setCurPos(pos)   [设置当前光标位置]
           参数:
                pos  {{Int}}  当前光标位置

*   (4)selectRange.getSelectText()   [获取选中文字]

*   (5)selectRange.setSelectText(startPos, endPos)   [选中特定范围的文本(只限于textarea和input)]
*           参数:
                startPos  {{Int}}  起始位置
                endPos  {{Int}}  终点位置

*   (6)selectRange.insertAfterText(value)   [在光标后插入文本]
*           参数:
                value  {{String}}  要插入的文本
* 
*
* ## 使用实例:
*       selectRange.of(EleDom).getCurPos(); // 获取当前坐标位置
*       selectRange.of(EleDom).setCurPos(pos); // 设置当前光标位置为pos
*       selectRange.of(EleDom).getSelectText(); // 获取选中文字
*       selectRange.of(EleDom).setSelectText(startPos, endPos); // 选中startPos到endPos范围的文本
*       selectRange.of(EleDom).insertAfterText(value); // 在光标后插入值为value的文本
*/

var selectRange = function(ele){
    this.__element = ele;
};
// 创建光标位置获取的新对象
selectRange.of = function(ele){
    if(ele) {
        return new selectRange(ele);
    } else {
        return {};
    }
};

selectRange.prototype = {
    constructor:selectRange,
    // 获取当前坐标位置
    getCurPos: function() {
        var _this = this,
            textDom = _this.__element;
        // 获取光标位置
        var cursorPos = 0;
        if (document.selection) {
            // IE Support
            textDom.focus();
            var selectRange = document.selection.createRange();
            selectRange.moveStart ('character', -textDom.value.length);
            cursorPos = selectRange.text.length;
        }else if (textDom.selectionStart || textDom.selectionStart == '0') {
            // Firefox support
            cursorPos = textDom.selectionStart;
        }
        return cursorPos;
    },

    /**
    * 设置当前光标位置
    * 参数:
    *     pos  [Int]  当前光标位置
    */
    setCurPos: function(pos) {
        var _this = this,
            textDom = _this.__element;
        if(textDom.setSelectionRange) {
            // IE Support
            textDom.focus();
            textDom.setSelectionRange(pos, pos);
        }else if (textDom.createTextRange) {
            // Firefox support
            var range = textDom.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    },

    // 获取选中文字
    getSelectText: function() {
        var _this = this,
            textDom = _this.__element,
            userSelection,
            text = "";
        if (window.getSelection) {
            // Firefox support
            userSelection = window.getSelection();
        } else if (document.selection) {
            // IE Support
            userSelection = document.selection.createRange();
        }
        if (!(text = userSelection.text)) {
            text = userSelection;
        }
        return text;
    },

    /**
    * 选中特定范围的文本(只限于textarea和input)
    * 参数:
    *     startPos  [Int]  起始位置
    *     endPos  [Int]  终点位置
    */
    setSelectText: function(startPos, endPos) {
        var _this = this,
            textDom = _this.__element,
            startPos = parseInt(startPos),
            endPos = parseInt(endPos),
            textLength = textDom.value.length;
        if(textLength){
            if(!startPos){
                startPos = 0;
            }
            if(!endPos){
                endPos = textLength;
            }
            if(startPos > textLength){
                startPos = textLength;
            }
            if(endPos > textLength){
                endPos = textLength;
            }
            if(startPos < 0){
                startPos = textLength + startPos;
            }
            if(endPos < 0){
                endPos = textLength + endPos;
            }
            if(textDom.createTextRange){
                // IE Support
                var range = textDom.createTextRange();
                range.moveStart("character",-textLength);
                range.moveEnd("character",-textLength);
                range.moveStart("character", startPos);
                range.moveEnd("character",endPos);
                range.select();
            }else{
                // Firefox support
                textDom.setSelectionRange(startPos, endPos);
                textDom.focus();
            }
        }
    },

    /**
    * 在光标后插入文本
    * 参数:
    *     value  [String]  要插入的文本
    */
    insertAfterText: function(value) {
        var _this = this,
            textDom = _this.__element,
            selectRange;
        if (document.selection) {
            // IE Support
            textDom.focus();
            selectRange = document.selection.createRange();
            selectRange.text = value;
            textDom.focus();
        }else if (textDom.selectionStart || textDom.selectionStart == '0') {
            // Firefox support
            var startPos = textDom.selectionStart;
            var endPos = textDom.selectionEnd;
            var scrollTop = textDom.scrollTop;
            textDom.value = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length);
            textDom.focus();
            textDom.selectionStart = startPos + value.length;
            textDom.selectionEnd = startPos + value.length;
            textDom.scrollTop = scrollTop;
        }
        else {
            textDom.value += value;
            textDom.focus();
        }
    }
};

// ===============================================
// 实例代码
var textareaDom = document.querySelector("#textarea"),
    setCurPosInput = document.querySelector("#input"),
    setCurPosBtn = document.querySelector("#setCurPosBtn"),
    selectText = document.querySelector("#selectText"),
    setSelectTextBtn = document.querySelector("#setSelectText"),
    insertAfterTextBtn = document.querySelector("#insertAfterText");
// 获取当前光标位置
textareaDom.addEventListener("keydown", function() {
    console.log("getCurPos: " + selectRange.of(textareaDom).getCurPos());
}, false);

// 设置当前光标位置
setCurPosBtn.addEventListener("click", function() {
    var curPos = parseInt(setCurPosInput.value);
    console.log("curPos: " + curPos);
    selectRange.of(textareaDom).setCurPos(curPos);
}, false);

// 获取选中文字
selectText.addEventListener("mouseup", function() {
    console.log("selectText: " + selectRange.of(this).getSelectText());
});

// 选中特定范围的文本
setSelectTextBtn.addEventListener("click", function() {
    selectRange.of(textareaDom).setSelectText(0, 21);
}, false);

// 在光标后插入文本
insertAfterTextBtn.addEventListener("click", function() {
    var insertText = "===hello world, I'm insert content.===";
    selectRange.of(textareaDom).insertAfterText(insertText);
}, false);
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console