现在的位置: 首页 > 综合 > 正文

javascript设置文本高亮显示

2018年01月23日 ⁄ 综合 ⁄ 共 759字 ⁄ 字号 评论关闭

//设置文本选中高亮

function setTextSelected(inputDom, startIndex, endIndex)
{
    if (inputDom.setSelectionRange)
    { 
        inputDom.setSelectionRange(startIndex, endIndex); 
    }  
    else if (inputDom.createTextRange) //IE
    {
        var range = inputDom.createTextRange(); 
        range.collapse(true); 
        range.moveStart('character', startIndex); 
        range.moveEnd('character', endIndex - startIndex-1); 
        range.select();
    } 
    inputDom.focus(); 
}

 

//获取选中文本
function getSelectedText(inputDom){ 
    if (document.selection) //IE
    {
        return document.selection.createRange().text;
    } 
    else { 
        return inputDom.value.substring(inputDom.selectionStart, 
                inputDom.selectionEnd); 
    } 
}

参数:

inputDom 为input 或者 textarea Dom 元素。

正常方式获取:

var inputDom = document.getElementById("input1");

抱歉!评论已关闭.