1、獲取選中的文字:
document.selection.createRange().text; IE9以下使用
window.getSelection().toString(); 其他瀏覽器使用
$('p').mouseup(function(){ var txt = window.getSelection?window.getSelection():document.selection.createRange().text; alert(txt) ; })
2、取消處於選中狀態的文字:
document.selection.empty(); IE9以下使用
window.getSelection().removeAllRanges(); 其他瀏覽器使用
$('p').mouseup(function(){ window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); })
上述方法不僅對div或p標簽中的文本有效(會自動忽略選中的‘圖片’),在ie和chrome中對input中的文本也有效,但在firefox中無效,jquery
的.select()事件(僅對input有效)或js的onselect事件(僅對input有效)和js的.select()(使input中的文本內容處於選中狀態)方法在三個瀏覽器中都有效。
可以用鼠標選中下段文字測試效果:
是他,是他,是他,就是他.我們的朋友小哪吒.是他,就是他,是他,就是他.少年英雄,小哪吒.上天他比~(稍長音),天要高~(同上).下海他比~(同上),海更大啊~啊~(同上).智斗妖魔~,勇降鬼怪.少年英雄,就是小哪吒.有時,他很聰明.有時,他也犯傻.他的個頭跟我一般高.有時,他很努力.有時,他也貪玩.他的年級和我一般大~~(長音).上天他比~(稍長音),天要高~(同上).下海他比~(同上),海更大啊~啊~(同上).智斗妖魔~,勇降鬼怪.少年英雄,就是小哪吒~~(長音).
3、使某Dom中的文字處於選中狀態:
IE中關於range參見http://msdn.microsoft.com/en-us/library/ie/ms536401%28v=vs.85%29.aspx
$('.somedom').click(function(){ /* not ok for firefox var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(this); selection.removeAllRanges();; selection.addRange(range);*/ this.focus(); if(window.getSelection){ var range=document.createRange(); range.selectNodeContents(this); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range) } else if(document.selection){ //for ie var range=document.body.createTextRange() range.moveToElementText(this) range.select(); }