我希望让用户单击一个链接,然后在另一个元素(不是输入)中选择HTML文本.
通过"选择",我的意思与通过将鼠标拖过它来选择文本的方式相同.这是一个研究的熊,因为每个人都在谈论其他术语中的"选择"或"突出".
这可能吗?我的代码到目前为止:
HTML:
<a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a>
<code id="xhtml-code">Some Code here </code>
Run Code Online (Sandbox Code Playgroud)
JS:
function SelectText(element) {
$("#" + element).select();
}
Run Code Online (Sandbox Code Playgroud)
我错过了一些明显的东西吗?
我使用鼠标在html页面(在firefox中打开)选择一些文本,并使用javascript函数,我创建/获取与所选文本对应的rangeobject.
userSelection =window.getSelection();
var rangeObject = getRangeObject(userSelection);
Run Code Online (Sandbox Code Playgroud)
现在我想突出显示rangeobject下的所有文本.我这样做,
var span = document.createElement("span");
rangeObject.surroundContents(span);
span.style.backgroundColor = "yellow";
Run Code Online (Sandbox Code Playgroud)
好吧,这个工作正常,只有当rangeobject(起始点和端点)位于同一个textnode中时,它才会突出显示相应的text.Ex
<p>In this case,the text selected will be highlighted properly,
because the selected text lies under a single textnode</p>
Run Code Online (Sandbox Code Playgroud)
但是如果rangeobject覆盖了多个textnode,那么它就不能正常工作,它只突出显示位于第一个textnode中的文本,Ex
<p><h3>In this case</h3>, only the text inside the header(h3)
will be highlighted, not any text outside the header</p>
Run Code Online (Sandbox Code Playgroud)
任何想法我怎么做,所有在rangeobject下的文本,突出显示,独立于范围是在单个节点还是多个节点?谢谢....
我想制作按钮,它将选择我的 p 标签中的所有文本。标签示例:
<p class="foo">
some text
<div>this div is child of p</div>
<div>one more row</div>
</p>
Run Code Online (Sandbox Code Playgroud)
解决方案也必须通过 window.getSelection() 或类似但不是 jQuery。我试图通过使用 selectNodeContents(el) 来做到这一点,但结果只是第一行。
任何人都可以帮助我,因为我无法弄清楚这一点。
编辑代码:
var selection = window.getSelection();
var txt = document.getElementsByClassName("foo");
var range = document.createRange();
range.selectNodeContents(txt);
selection.removeAllRanges();
selection.addRange(range);
Run Code Online (Sandbox Code Playgroud)