Firefox选择文本范围 [英] Firefox select text range
本文介绍了Firefox选择文本范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
在Firefox中,您可以使用范围对象,如 W3C 所指定。
<!DOCTYPE html>
< html>
< head>
< meta charset =UTF-8>
< title>范围测试< /标题>
< style>
#trigger {background:lightgreen}
< / style>
< / head>
< body>
< p id =test>这是一些(相当短的)文字。< / p>
< span id =trigger>→点击这里! ←< /跨度>
<! - 是的,我知道'点击这里'是一个邪恶的信息 - >
< script>
var testCase = function(){
var userSelection;
if(window.getSelection){// W3C default
userSelection = window.getSelection();
} //如果你想支持IE
,额外的分支将是必要的。var textNode = document.getElementById('test')。firstChild;
var theRange = document.createRange();
//选择第10到第15个字符(从0开始计数)
theRange.setStart(textNode,9);
theRange.setEnd(textNode,14);
//设置用户选择
userSelection.addRange(theRange);
};
window.onload = function(){
var el = document.getElementById('trigger');
el.onclick = testCase;
};
< / script>
< / body>
< / html>
请注意,您必须获取 TextNode
设置< p>
元素的选项,即 firstChild
。另外请注意,这个例子在IE中不起作用,你必须使用一些专有的方法。好的介绍在 QuirksMode 。
A quick question: how do I programatically select the text fragment of the page in FireFox? For example, there's a paragraph of text, user clicks the button and symbols from 10-th to 15-th are selected as if user dragged a mouse in a regular way.
解决方案
In Firefox, you can use the Range object, as specified by W3C.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Range test</title>
<style>
#trigger { background: lightgreen }
</style>
</head>
<body>
<p id="test">This is some (rather short) text.</p>
<span id="trigger">→ Click here! ←</span>
<!-- Yes, I know, ‘Click here!’ is an evil message -->
<script>
var testCase = function () {
var userSelection;
if (window.getSelection) { // W3C default
userSelection = window.getSelection();
} // an extra branch would be necessary if you want to support IE
var textNode = document.getElementById('test').firstChild;
var theRange = document.createRange();
// select 10th–15th character (counting starts at 0)
theRange.setStart(textNode, 9);
theRange.setEnd(textNode, 14);
// set user selection
userSelection.addRange(theRange);
};
window.onload = function () {
var el = document.getElementById('trigger');
el.onclick = testCase;
};
</script>
</body>
</html>
Note that you have to get the TextNode
to set the selection, which is the firstChild
of the <p>
element. Also note that this example will not work in IE, you have to use some proprietary methods. A nice introduction is on QuirksMode.
这篇关于Firefox选择文本范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文