选择元素中的文本(类似于用鼠标突出显示) [英] Selecting text in an element (akin to highlighting with your mouse)
问题描述
我希望用户点击一个链接,然后选择另一个元素中的HTML文本(不输入)。
I would like to have users click a link, then it selects the HTML text in another element (not an input).
通过选择,我的意思与通过将鼠标拖过它来选择文本的方式相同。这是一个研究熊,因为每个人都在谈论其他术语中的选择或突出显示。
By "select" I mean the same way you would select text by dragging your mouse over it. This has been a bear to research because everyone talks about "select" or "highlight" in other terms.
这可能吗?到目前为止我的代码:
Is this possible? My code so far:
HTML:
<a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a>
<code id="xhtml-code">Some Code here </code>
JS:
function SelectText(element) {
$("#" + element).select();
}
我错过了一些明显的东西吗?
Am I missing something blatantly obvious?
推荐答案
普通Javascript
Plain Javascript
function selectText(node) {
node = document.getElementById(node);
if (document.body.createTextRange) {
const range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
} else {
console.warn("Could not select text in node: Unsupported browser.");
}
}
const clickable = document.querySelector('.click-me');
clickable.addEventListener('click', () => selectText('target'));
<div id="target"><p>Some text goes here!</p><p>Moar text!</p></div>
<p class="click-me">Click me!</p>
这是工作演示。对于那些寻找jQuery插件的人,我做了其中之一。
Here is a working demo. For those of you looking for a jQuery plugin, I made one of those too.
我找到了一个解决方案在此主题中。我能够修改给定的信息并将其与一些jQuery混合,以创建一个非常棒的函数来选择任何元素中的文本,无论浏览器如何:
I have found a solution for this in this thread. I was able to modify the info given and mix it with a bit of jQuery to create a totally awesome function to select the text in any element, regardless of browser:
function SelectText(element) {
var text = document.getElementById(element);
if ($.browser.msie) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if ($.browser.mozilla || $.browser.opera) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
} else if ($.browser.safari) {
var selection = window.getSelection();
selection.setBaseAndExtent(text, 0, text, 1);
}
}
这篇关于选择元素中的文本(类似于用鼠标突出显示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!