JS 怎么获取文本框中选中的文字

JavaScript011

JS 怎么获取文本框中选中的文字,第1张

//获取选中的文字

function getSelectText(editor) {

    if (!editor) return editor.focus()

    if (editor.document && editor.document.selection)

        return editor.document.selection.createRange().text 

    else if ("selectionStart" in editor)

        return editor.value.substring(editor.selectionStart, editor.selectionEnd) 

}

//调用方式

var text= getSelectText(document.getElementById("txtName"))

1:先获取textarea中的文本2:用字符串的split()方法以你需要的某段文字切割成数组3:在用数组中的join()方法把你需要的某段文字加上标签样式返回成字符串4:重新把join()返回过来的文本赋值给textarea