我在html文档中检测长按(触摸事件)中的单词。但是长期以来我得到原生文本选择器。我尝试通过CSS禁用用户选择,如下所示,但它会导致错误。
html {
-webkit-user-select: none;
}
错误:
Uncaught IndexSizeError: Index or size was negative, or greater than the allowed value.
代码:
<body onload="init()">
<p id="book-content">
One reason people ......at the time, since then it has made me look down on myself.
</p>
<script type="text/javascript">
var self = this;
var startTime, endTime;
var gbMove = false;
function init() {
document.getElementById("book-content").addEventListener('touchstart', self.touchstart, false);
document.getElementById("book-content").addEventListener('touchmove', self.touchmove, false);
document.getElementById("book-content").addEventListener('touchend', self.touchend, false);
}
function touchstart(e) {
startTime = new Date().getTime();
gbMove = false;
console.log('Received Event touchstart');
}
function touchmove(e) {
// gbMove = true;
console.log('Received Event touchmove');
}
function touchend(e) {
endTime = new Date().getTime();
if (!gbMove && (endTime - startTime) / 1000 > 1) {
s = window.getSelection();
var range = s.getRangeAt(0);
var node = s.anchorNode;
while (range.toString().indexOf(' ') != 0) {
range.setStart(node, (range.startOffset - 1));
}
range.setStart(node, range.startOffset + 1);
do {
range.setEnd(node, range.endOffset + 1);
} while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '' && range.endOffset < node.length);
var str = range.toString().trim();
alert(str);
}
}
</script>
</body>
答案 0 :(得分:0)
这个问题很容易预防。在调用getRangeAt之前始终检查rangeCount:
function touchend(e) {
...
if (s && s.rangeCount > 0) {
var range = s.getRangeAt(0);
...
}
请参考 - 同样的问题解决here in this post。在这里摆弄http://jsfiddle.net/stXDu/