DIV의 DOM 노드 및 텍스트 선택

3309 단어 div


/**
* @description           。
*  el{DOMElement}         。
*   text   ,    el  text  。
* @author shawn
*/
function selectDomText(el,text) {
    if(!el)    
        return;
    if(text){
        if(/MSIE ([^;]+)/.test(navigator.userAgent)){
            var range = document.body.createTextRange();
            range.moveToElementText(el);
            var found = range.findText(text);
            if(found){
                range.execCommand('selectAll');
            }
        }else{
            var t = el.firstChild;
            if(t && t.nodeType == 3){
                var range = document.createRange();
                var str = t.nodeValue;
	            range.selectNode(t);
                var idx = str.indexOf(text);
                if(idx != -1){
                    var selObj = window.getSelection();
                    selObj.removeAllRanges();
                    range.setStart(t,idx);
                    range.setEnd(t,idx + text.length);
                    selObj.addRange(range);
                }
            }
        }
    }else{
        if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                selection.selectAllChildren (el);
        } else {                    // Internet Explorer before version 9
                var range = document.body.createTextRange ();
                range.moveToElementText (el);
                range.select();
        }
    }
}
/**
*       ,  body/input/textarea  。
*/
function getSelText(){
    var selText = "";
    if (window.getSelection) {  // all browsers, except IE before version 9
        if (document.activeElement && 
                (document.activeElement.tagName.toLowerCase () == "textarea" || 
                 document.activeElement.tagName.toLowerCase () == "input")) 
        {
            var text = document.activeElement.value;
            selText = text.substring (document.activeElement.selectionStart, 
                                      document.activeElement.selectionEnd);
        }
        else {
            var selRange = window.getSelection ();
            selText = selRange.toString ();
        }
    }
    else {
        if (document.selection.createRange) { // Internet Explorer
            var range = document.selection.createRange ();
            selText = range.text;
        }
    }
    return selText;
}

//          
function selectText(textbox, startIndex, stopIndex){
	if (textbox.setSelectionRange){
		textbox.setSelectionRange(startIndex, stopIndex);
	} else if (textbox.createTextRange){
		var range = textbox.createTextRange();
		range.collapse(true);
		range.moveStart(“character”, startIndex);
		range.moveEnd(“character”, stopIndex - startIndex);
		range.select();
	}
	textbox.focus();
}

좋은 웹페이지 즐겨찾기