我正在为选择对象添加范围
var selection = window.getSelection();
selection.addRange(range);
在不同的页面上添加相同的范围时,选择对象的属性是不同的。
所需的选择对象
Selection {type: "Range", extentOffset: 1, extentNode: div#hiddenarea, baseOffset: 0, baseNode: div#hiddenarea…}
不受欢迎的选择对象
Selection {type: "Caret", extentOffset: 19, extentNode: text, baseOffset: 19, baseNode: text…}
选择类型插入符号的含义是什么以及如何将其设置为Range。
随着我的探索,我可以看到当我们最初创建选择对象时问题就出现了
var selection = window.getSelection();
所需
selection: Selection
anchorNode: null
anchorOffset: 0
baseNode: null
baseOffset: 0
extentNode: null
extentOffset: 0
focusNode: null
focusOffset: 0
isCollapsed: true
rangeCount: 0
type: "None"
__proto__: Selection
不受欢迎
selection: Selection
anchorNode: text
anchorOffset: 19
baseNode: text
baseOffset: 19
extentNode: text
extentOffset: 19
focusNode: text
focusOffset: 19
isCollapsed: true
rangeCount: 1
type: "Caret"
__proto__: Selection
答案 0 :(得分:1)
试试这个兄弟。
<script type="text/javascript">
function SelectFirstLine () {
var elemToSelect = document.getElementById ("firstLine");
if (window.getSelection) { // all browsers, except IE before version 9
var selection = window.getSelection ();
var rangeToSelect = document.createRange ();
rangeToSelect.selectNodeContents (elemToSelect);
selection.removeAllRanges ();
selection.addRange (rangeToSelect);
} else {
if (document.body.createTextRange) { // Internet Explorer
var rangeToSelect = document.body.createTextRange ();
rangeToSelect.moveToElementText (elemToSelect);
rangeToSelect.select ();
}
}
}
</script>
希望它可以帮助你:)