如何使用" window.getSelection()"来获取HTML

时间:2013-01-26 08:07:39

标签: javascript internet-explorer google-chrome w3c

我的代码:

<p id="p">
    123<span>abc</span>456
</p>
<script>
    document.getElementById("p").onmouseup=function(){
         if (window.getSelection) {
             //code
         }
         else if (document.selection) {   
             alert(document.selection.createRange().htmlText)  //IE6 7 8
         }
    }
</script>

在“// code”处写什么我可以在chrome或FF中获得相同的htmlText?

1 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/kyP83/

document.getElementsByTagName('p')[0].onmouseup = function() {
    if (typeof window.getSelection === 'function') {
        //code
        var selObj = window.getSelection(); 
        alert(selObj);
        var selRange = selObj.getRangeAt(0);             
    } else if (document.selection) {   
        alert(document.selection.createRange().htmlText)  //IE6 7 8
    }
}
相关问题