Javascript window.getSelection() 长度为 0,而使用 querySelector
Javascript window.getSelection() length 0 while using querySelector
我正在尝试使用 window.getSelection.getRangeAt(0) 获取所选文本这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function Selected(){
var range = window.getSelection().getRangeAt(0);
alert(range);
content = range.cloneContents();
var select = content.querySelectorAll('span');
alert(select.length);
}
</script>
</head>
<body >
<span style="font-size:45px" onmouseup="Selected()" id="idNo1">This is some text</span>
</body>
</html>
警报(选择长度);总是 0 有人可以帮助我解决这个问题。谢谢。但范围包含所选文本。
你不能这样做
来获取选定的字符串长度吗?alert(range) 正在执行 range.toString()
<!DOCTYPE html>
<html>
<head>
<script>
function Selected(){
var range = window.getSelection().getRangeAt(0);
// to get the text ( it does range.toString() )
alert(range);
// to get the text length
alert(range.toString().length);
// to get the id of the startNode
alert(range.startContainer.parentNode.id);
}
</script>
</head>
<body >
<span style="font-size:45px" onmouseup="Selected()" id="idNo1">This is some text</span>
</body>
</html>
答案和一些有用的相关位:
所选文本:
window.getSelection().toString();//pa'rtially selected tex't.
window.getSelection().toString().length;//20, length of the selected text.
锚节点(开始初始文本拖动的位置)中的文本可以位于左侧或右侧:
window.getSelection().anchorNode;//Node text, NOT selection text.
window.getSelection().anchorNode.length;//Length of node's text, not selection.
焦点节点(文本初始拖动结束的位置)中的文本可以位于左侧或右侧:
window.getSelection().focusNode;//Node text, NOT selection text.
window.getSelection().focusNode.length;//Length of node's text, not selection.
所选文本的共同祖先(实际上是parentNode
):
window.getSelection().getRangeAt(0).commonAncestorContainer
删除所选文本:
window.getSelection().deleteFromDocument();
相关文章:
- querySelector/getElementByClassName嵌套项的顺序
- 如何找到家长's的子级,使用querySelector而不是jQuery
- 使用querySelector()获取最后一个td元素
- 如何在JS中修饰querySelector/querySelectorAll
- Javascript .querySelector 通过 innerTEXT 查找
- 在 document.querySelector 中使用变量
- Why does "document.querySelector('a.some class'
- “*[attribute ^="string”是如何/为什么是有效的querySelector?(JS bug
- Jest - querySelector('html, body') 返回奇怪的对象
- Javascript window.getSelection() 长度为 0,而使用 querySelector
- document.querySelector(".class h1")
- 生成一个链接到querySelector上的函数
- document.querySelector issues
- document.querySelector(...) is null error
- querySelector() attachEvent() not working
- 父>querySelector中的子选择器
- querySelector位于特定元素之后
- 未捕获的类型错误:无法读取属性'querySelector'的未定义
- xml文件中的Javascript querySelector CDATA
- 转义 JavaScript 中 querySelector 的前导数字类名