gpt4 book ai didi

javascript - 在 Javascript 中定位突出显示的文本

转载 作者:太空狗 更新时间:2023-10-29 14:56:24 27 4
gpt4 key购买 nike

寻找一种方法来定位选定的文本并在 Javascript 中对其执行操作。我应该使用什么样的方法?这是 jQuery 的工作吗?非常感谢!

编辑:早期的答案被视为针对 CSS 类。我正在寻找单击并突出显示/选择文本,然后在 JS 中对其进行操作。谢谢!

编辑 2:有人要求我提供此功能的示例。 Here's一个但是代码评论很差。让我知道您的想法。

最佳答案

编写跨浏览器的通用“获取选定文本”功能非常困难。如果您可以将您的要求限制为仅说出页面中选定的文本,那么生活就会更简单。

但是,如果您希望能够从任何地方(在表单控件内、按钮标签、一般文本内)获取文本选择,那么生活就很艰难了。

这是我前段时间写的一个函数,它在使用它的应用程序中工作得很好:

/* 
* This function returns the selected text in a document.
* If no text selected, returns an empty string.
*
* Call on one of the following events:
*
* mouseup - most appropriate event
* for selection by mousedown, drag to select, mouseup
* may select only whitespace
*
* dblclick - not as appropriate as mouseup
* for selection of word by double click
* may select only whitespace
*
* Note that text can be selected in ways that do not dispatch
* an event, e.g. selecting all the text in the document using:
* ctrl + a
* context menu -> Select All
* edit menu -> Select All
* programmatically selecting text
*/
function checkForSelectedText(e) {
var e = e || window.event;
var el = e.target || e.srcElement;
var tagName = el.tagName && el.tagName.toLowerCase();
var t;
var d = document;

// Try DOM 2 Range - for most browsers, including IE 6+
// However, doesn't get text selected inside form controls
// that allow selection of text content (input type text,
// textarea)
if (d && d.selection && d.selection.createRange) {
t = d.selection.createRange().text;

// Otherwise try HTML5 - note that getSelection returns
// a string with extra properties. This may also get
// text within input and textarea
} else if (d.getSelection) {
t = d.getSelection();
}

// If didn't get any text, see if event was inside
// inupt@type=text or textarea and look for text
if (t == '') {
if (tagName == 'textarea' ||
(tagName == 'input' && el.type == 'text')) {

// Check selectionStart/End as otherwise if no text
// selected, IE returns entire text of element
if (typeof el.selectionStart == 'number' &&
el.selectionStart != el.selectionEnd) {
t = el.value.substring(el.selectionStart, el.selectionEnd)
}
}
}
return t;
}

关于javascript - 在 Javascript 中定位突出显示的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8263953/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com