項目中用到鼠標獲取頁面內容,要粘貼到別的頁面,在進行粘貼的內容進行變色處理。這次只是做寫選中頁面的內容進行處理操作。
現在直接上代碼內容不多:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span onClick="SelectText()">時間的長河在歲月的痕跡中是相輔相成的。時間是歲月的伴隨者,又怎麼能說明兩者的關係呢......</span>
<script>
function SelectText(){
try{
var selecter=window.getSelection().toString();
if(selecter!=null&&selecter.trim()!=""){
alert(" 1 " + 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,"");
}
</script>
</html>
有需要的可以直接複製上面的代碼進行相應 的改動就可以了。
如果幫到你請點擊一下關注。