Javascript 在文本突出显示事件中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3731328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
On Text Highlight Event?
提问by Robert Smith
I'm curious if anyone knows how I would trigger a function to run if/once the user finishes selecting text on the web page? I would like the user to be able to select text, and after a short delay(or immediately, at this point it doesn't matter much) an overlay button appears near the text that the user can then click and I go back and run more of my code that is based on the selection. This is for a Firefox extension.
我很好奇是否有人知道如果/一旦用户完成在网页上选择文本,我将如何触发函数运行?我希望用户能够选择文本,并在短暂延迟(或立即,此时无关紧要)后,在用户可以单击的文本附近出现一个覆盖按钮,然后我返回并运行更多基于选择的代码。这是用于 Firefox 扩展。
A similar example that I can think of would be like in IE where you can select text and then it brings up the "web accelerators". I'm 99% sure I know how I would actually overlay the button, and get the position of the selected text, but I have no idea how to check to see if there is anything selected, without doing some sort of infinite loop, which just seems like a terrible idea.
我能想到的一个类似示例就像在 IE 中,您可以在其中选择文本,然后它会显示“网络加速器”。我 99% 确定我知道我将如何实际覆盖按钮并获取所选文本的位置,但我不知道如何检查是否有任何选择,而不做某种无限循环,这只是似乎是一个可怕的想法。
EDIT:
编辑:
//In my overlay.js with the rest of my sidebar code
isTextSelected: function () {
var myText = cqsearch.getSelectedText();
var sidebar = document.getElementById("sidebar");
var sidebarDoc = sidebar.contentDocument || document;
var curHighlightedDiv = sidebarDoc.getElementById("testDiv");
curHighlightedDiv.innerHTML = "Current text selection:" + myText;
}
};
//In my on firefox load function I added this
document.onmouseup = cqsearch.isTextSelected;
So this is what I have come up with using Robert's suggestion, and it took me some time getting everything in the right spot, but it works great! Now on to position my button.
所以这就是我使用罗伯特的建议提出的,我花了一些时间把所有东西都放在正确的位置,但效果很好!现在来定位我的按钮。
回答by Robert
There isn't any onhighlightext
or anything like that, but a solution would be to bind onmouseup
to check if any text is selected if this isn't in a input
/textarea
.
没有任何onhighlightext
类似的东西,但解决方案是绑定onmouseup
以检查是否选择了任何文本,如果它不在input
/ 中textarea
。
Edit
编辑
Here's an implementation example for you. I only tested this in Chrome/Firefox/IE7. This works in inputs as well.
这是一个为您提供的实现示例。我只在 Chrome/Firefox/IE7 中测试过。这也适用于输入。
Code from JSFiddle:
来自JSFiddle 的代码:
var t = '';
function gText(e) {
t = (document.all) ? document.selection.createRange().text : document.getSelection();
document.getElementById('input').value = t;
}
document.onmouseup = gText;
if (!document.all) document.captureEvents(Event.MOUSEUP);
<input type='text' id='input' />
In software, a stack overflow occurs when too much memory is used on the call stack. The call stack contains a limited amount of memory, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When too much memory is used on the call stack the stack is said to overflow, typically resulting in a program crash.[1] This class of software bug is usually caused by one of two types of programming errors.[2]
回答by jarsbe
A bit late to the party but for future reference...
聚会有点晚了,但以备将来参考......
Take a look at the select
DOM event on MDN.
看看MDN上的select
DOM 事件。
It fires once the mouse or key is released (at least in Chrome 40).
一旦释放鼠标或键,它就会触发(至少在 Chrome 40 中)。
document.addEventListener('select', callback);
document.addEventListener('select', callback);
回答by Patrick Evans
There is a native event for when a text selection is made / changed. selectionchange
has basic support on most browsers, including IE, and will work for any text within a document not just form elements.
当进行文本选择/更改时有一个本机事件。对包括 IE 在内的大多数浏览器selectionchange
都有基本的支持,并且适用于文档中的任何文本,而不仅仅是表单元素。
document.addEventListener("selectionchange",event=>{
let selection = document.getSelection ? document.getSelection().toString() : document.selection.createRange().toString() ;
console.log(selection);
})
select this text
Note, as its name implies it fires on the any change of a selection. So you will get multiple calls to your callback function as you select text.
请注意,顾名思义,它会在选择的任何更改时触发。因此,您将在选择文本时多次调用回调函数。
回答by Marshal
I'd suggest listening to mouseup event rather than selectionchange as the latter fires quite many events (up to the chars selected), you have to wait some arbitrary period to get the final selection. Ditto @Robert and @Makyen, I've created some code for you to play:
我建议收听 mouseup 事件而不是 selectionchange ,因为后者会触发很多事件(直到选择的字符),您必须等待一段时间才能获得最终选择。同上@Robert 和@Makyen,我已经创建了一些代码供您玩:
<!DOCTYPE html>
<html>
<body>
<div onmouseup="showSelection()">
<p>Select some of the text. You can also listen to the mouseup event at the <p> level</p>
<p>Anthoer paragraph and text</p>
<input type="text" value="Hello world!" onselect="showSelection()">
</div>
Outside of div, selection won't work as there is no listener if you don't uncomment the line: document.onmouseup = showSelection
<script>
// document.onmouseup = showSelection // listen to the mouseup event at document level
function showSelection() {
console.log('Selection object:', window.getSelection()) // same as document.getSelection()
console.log('Selected text:', window.getSelection().toString())
}
</script>
</body>
</html>
回答by Cybernetic
Just handle the mouseupevent, since a user "lets go" of the key after highlighting:
只需处理mouseup事件,因为用户在突出显示后“放开”键:
Vanilla JS
香草JS
//Directly within element
<p class='my_class' onmousedown="my_down_function()" onmouseup="my_up_function()">
//On element
my_element = document.querySelector('.my_class');
my_element.onmousedown = function (e) { my_down_function(e); };
my_element.onmouseup function (e) { my_up_function(e); };
jQuery
jQuery
$('.my_class').mousedown(function() {
my_down_function()
})
$('.my_class').mouseup(function() {
my_up_function()
})
az.add_event('my_class', 1, {
"type" : "mousedown",
"function" : "my_down_function()"
})
az.add_event('my_class', 1, {
"type" : "mouseup",
"function" : "my_up_function()"
})
回答by waffledonkey
I think @patrick-evans had the right answer. It's easily the most forward-thinking and API supportedanswer -- you just need to debounce the event to stop the deluge.
我认为@patrick-evans 有正确的答案。这很容易成为最具前瞻性和 API 支持的答案——您只需要对事件进行去抖动即可阻止洪水泛滥。
I'm not able to post a reply, but consider this
我无法发表回复,但请考虑一下
function debounce(fn, delay) {
let timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
};
document.addEventListener("selectionchange", debounce(function (event) {
let selection = document.getSelection ? document.getSelection().toString() : document.selection.createRange().toString() ;
console.log(selection);
}, 250));
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad est veniam facere culpa expedita optio iste labore doloremque autem illo, in voluptatibus error ea, ab reprehenderit placeat facilis animi iure?
回答by Noitidart
The solution using the mouseup trick is not the proper solution. That is a hacky way and not perfect. Less efficient too as you are now catching mouseups for so much crap.
使用 mouseup 技巧的解决方案不是正确的解决方案。这是一种骇人听闻的方式,并不完美。效率也较低,因为您现在正在为这么多废话捕捉鼠标。
The real way to do it in Firefox addon is to use addSelectionListener
see this topic: Observe for highlight?
在 Firefox 插件中执行此操作的真正方法是使用addSelectionListener
查看此主题:Observe for highlight?
Now even if user uses keyboard to make selections it is caught.
现在,即使用户使用键盘进行选择,它也会被捕获。
Credit to Neil for tipping me off on where to find it on MXR
感谢 Neil 告诉我在 MXR 上哪里可以找到它