得到Textarea光标的位置

       //得到光标的位置
            getCursorPosition:function(textarea){
                // 光标位置
                var end = textarea.selectionEnd
                // 光标前的内容
                var beforeText = textarea.value.slice(0, end)
                // 光标后的内容
                var afterText = textarea.value.slice(end)
                // 对影响 UI 的特殊元素编码
                var escape = function(text) {
                    return text.replace(/<|>|`|"|&/g, '?').replace(/\r\n|\r|\n/g, '<br>')
                }
                // 创建镜像内容,复制样式
                var mirror = '<div class="cursorBox">'
                                + escape(beforeText)
                                + '<span id="cursor">|</span>'
                                + escape(afterText)
                            + '</div>'
                // 添加到 textarea 同级,注意设置定位及 zIndex,使两个元素重合
                textarea.insertAdjacentHTML('afterend', mirror)
                // 通过镜像元素中的假光标占位元素获取像素位置
                var cursor = document.getElementById('cursor')
          cursor.getBoundingClientRect()  // { width, height, top, right, bottom, right }
            }

样式:

.cursorBox{
    position:absolute;
    top:10px;
    width:470px;
    z-index:-1;
}

 

posted @ 2018-02-24 17:35  rachelch  阅读(325)  评论(0)    收藏  举报