需求:1.獲取網頁頁面選中的文字
2.填充至指定文本框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../jQuery-3.3.1.min.js"></script>
</head>
<body>
<div id="content" style="width:300px; margin:50px;">
一半灰暗一半蔚藍<br>
雲飛得好快<br>
一個人瞧着窗外<br>
移動在這漂浮城市<br>
車往風裏開
</div>
<select class="insert-position">
<option>標題</option>
<option>內容</option>
</select>
<input type="text" class="title" />
<input type="text" class="content" />
<script>
$(function () {
$('#content').on("mouseup ",function(){
//alert(selectText());
//var str=document.execCommand("Copy");
function setSelect() {
var val,$item;
switch ($(".insert-position").val()) {
case("標題"):
$item=$(".title");
break;
case ("內容"):
$item=$(".content");
break;
default:
$item=$(".title");
}
val=$item.val()+selectText();
$item.val(val);
}
setSelect();
});
function selectText(){
if(document.Selection){
//ie瀏覽器
return document.selection.createRange().text;
}else{
//標準瀏覽器
return window.getSelection().toString();
}
}
})
</script>
</body>
</html>
參考鏈接: