[英]get selected texts inside content editable elements
我想進行文本編輯,並更改內容可編輯元素內部的文本,並由用戶選擇。
我的問題是: 如何在內容可編輯元素中獲取選定的文本?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="D:\JQueryPath\jquery-3.1.1.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#show").click(function(){
//alert("selected texts");
});
});
</script>
</head>
<body>
<div id="textEditor" style=" border:solid 1px #D31444" contenteditable="true" ></div>
<p></p>
<button id="show">show selected elements</button>
</body>
</html>
這將使您入門,盡管您將需要考慮擴展此代碼以適應有人在您的文本區域之外進行選擇以及有人按下按鈕而未選擇任何內容的情況。
哦,我讓控制台記錄了輸出而不是警告它。
$(document).ready(function(){
$("#show").click(function(){
range = window.getSelection().getRangeAt(0);
console.log(range.toString());
});
});
您可以使用window.getSelection()
方法。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="D:\JQueryPath\jquery-3.1.1.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#show").click(function(){
alert(window.getSelection().toString());
});
});
</script>
</head>
<body>
<div id="textEditor" style=" border:solid 1px #D31444"contenteditable="true" ></div>
<p></p>
<button id="show">show selected elements</button>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.