js通过selection获取选中元素

function getSelectedHtml(){
    var selectedHtml = "";
    var documentFragment = null;

    try{
        if(window.getSelection){
            documentFragment =  window.getSelection().getRangeAt(0).cloneContents();
        }else if(document.selection){
            documentFragment =  document.selection.createRange().HtmlText;
        }

        for(var i=0;i<documentFragment.childNodes.length;i++){
            var childNode = documentFragment.childNodes[i];
            if(childNode.nodeType==3){ // Text 节点
                selectedHtml+=childNode.nodeValue;
            }else{
                var nodeHtml = childNode.outerHTML;
                selectedHtml+=nodeHtml;
            }

        }

    }catch(err){

    }

    return selectedHtml;
}


你可能感兴趣的:(html,js,selection)