定义需要获取的内容的节点:
<span onClick="SelectText()">河中鱼类离奇死亡,下游居民频染怪病,
沿岸植物不断变异,是残留农药?还是生化攻击?》</span>
获取选中的文字,我们使用window.getSelection().toString()
方法。
代码如下:
function SelectText()
{
try{
var selecter=window.getSelection().toString();
if(selecter!=null&&selecter.trim()!=""){
alert(selecter);
}
}catch(err){
var selecter=document.selection.createRange();
var s=selecter.text;
if(s!=null&&s.trim()!=""){
alert(s)
}
}
}
//替换文本前与后的空格
String.prototype.trim=function()
{
return this.replace(/(^\s*)|(\s*$)/g,"");
}
JS获取鼠标选中的值
if (window.getSelection)
{//一般浏览器
userSelection = window.getSelection();
}
else if (document.selection)
{//IE浏览器、Opera
userSelection = document.selection.createRange();
} userSelection.toString();
js获取div中鼠标选中的文本内容
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div><p onmouseup="mytest()">只是一段文本其余的还有很多的文字</p></div>
<script>
function mytest(e){
console.log(window.getSelection);
var txt = window.getSelection?window.getSelection():document.selection.createRange().text;
if(txt==""){//当选中内容为空时,阻止事件发生
window.event? window.event.cancelBubble = true : e.stopPropagation();
}else{
var txt1=String.toString(txt);//得到的选中的文本是一个对象,需要转化为字符串
alert(txt1);
}
}
</script>
</body>
</html>
js获取鼠标选中的文字
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中的文字处于选中状态:
$('.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();
}