在javascript中有兩個名爲selection和getSelection的對象。現在「選擇」有很多屬性和方法。例如toString,Modify等方法。選擇和getSelection。我應該使用哪個對象?
我遇到的問題是我應該使用哪個版本的對象選擇還是getSelection?
在caniuse.com
在javascript中有兩個名爲selection和getSelection的對象。現在「選擇」有很多屬性和方法。例如toString,Modify等方法。選擇和getSelection。我應該使用哪個對象?
我遇到的問題是我應該使用哪個版本的對象選擇還是getSelection?
在caniuse.com
試試這個--------------------
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function SelectText() {
var input = document.getElementById("mytextbox");
input.focus();
input.setSelectionRange(2, 5);
var selObj = Window.toString();
//window.getselection returs the object of current selection
alert(selObj);
}
</script>
</head>
<body>
<p><input type="text" id="mytextbox" size="20" value="getselection" /></p>
<p><button onclick="SelectText()">Select text</button></p>
</body>
</html>
那些沒有信息是不一樣的事情:getSelection
返回頁面上的當前選擇作爲一個對象,它是的Selection
一個實例。由於getSelection
返回的對象是Selection
的實例,因此它將繼承其所有方法和屬性(包括toString,修改等等)。因此,要解決您的問題,您必須getSelection
才能獲取,設置和修改頁面上的選擇。
有些文檔here on MDN
Try this .. you may get an idea about version support and getselection
<head>
<script type="text/javascript">
function GetSelectedText() {
var selText = "";
if (window.getSelection) {
// Supports all browsers, except IE before version 9
if (document.activeElement &&
(document.activeElement.tagName.toLowerCase() == "textarea" ||
document.activeElement.tagName.toLowerCase() == "input")) {
var text = document.activeElement.value;
selText = text.substring(document.activeElement.selectionStart,
document.activeElement.selectionEnd);
}
else {
var selRange = window.getSelection();
selText = selRange.toString();
}
}
else {
if (document.selection.createRange) {
// for Internet Explorer
var range = document.selection.createRange();
selText = range.text;
}
}
if (selText !== "") {
alert(selText);
}
}
</script>
</head>
<body onmouseup="GetSelectedText()">
Some text for selection.
<br /><br />
<textarea>Some text in a textarea element.</textarea>
<input type="text" value="Some text in an input field." size="40" />
<br /><br />
Select some content on this page!
</body>
如何爲瀏覽器支持反正?我聽到ie11刪除「選擇」 – Asperger
瀏覽器支持IE 9不超過 –