jQuery:仅在特定 div 中触发 keydown
我有一个包含几个 DIV 元素的页面。当用户按下 CTRL+ENTER 按钮组合时,我需要显示(通过alert())用户之前选择的文本。我找到了解决方案它就像一种魅力,但仍然剩下一件事。
仅当所选文本位于类为“main_content”的 DIV 内时,我才需要触发事件。我尝试将 keyup
分配给 $('DIV.main_content'),但它不起作用。
有没有办法仅在选择 $('DIV.main_content') 内的文本时才触发事件?
以下是在整个文档上触发的工作代码:
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
$(document).ready(function(){
$(document).keydown(function(e) {
if(e.which == 13 && e.ctrlKey) {
alert(getSelectedText());
return false;
}
});
});
I have a page with couple of DIV elements. When user presses the CTRL+ENTER button combo, I need to display (via alert()) the text, that user previously selected. I found the solution and it works like a charm, but there is still one thing left.
I need to make event trigger, only when selected text is inside a DIV with class "main_content". I've tried to assign keyup
to $('DIV.main_content'), but it does not work.
Is there a way to make event trigger only if text inside $('DIV.main_content') selected?
Here is a working code that triggers on the whole document:
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
$(document).ready(function(){
$(document).keydown(function(e) {
if(e.which == 13 && e.ctrlKey) {
alert(getSelectedText());
return false;
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getSelectedText()
函数中出现错误:window.getSelection()
返回一个Selection
对象,而不是字符串。您将其结果传递给alert()
的事实掩盖了这一点,因为alert()
隐式地将传递给它的参数转换为字符串。下面是一些代码,用于检查选择是否完全包含在具有特定类的
元素中。它适用于所有主要浏览器。
实例:http://www.jsfiddle.net/cVgsy/1/
You have an error in the
getSelectedText()
function:window.getSelection()
returns aSelection
object, not a string. The fact you're passing the result of this toalert()
is masking this, becausealert()
implicitly converts the argument passed to it into a string.Here's some code to check whether the selection is completely contained within a
<div>
element with a particular class. It works in all major browsers.Live example: http://www.jsfiddle.net/cVgsy/1/
这是一个有趣的问题。我有以下想法:您需要捕获 div 上的 mouseup 事件。
例如:
因此,在您的情况下,您可以执行以下操作:
变量 selectedText 将存储选定的文本。
It is interesting question. I have the following idea: you need to catch mouseup event on div.
For example:
So, in your case you can do something like this:
And variable selectedText will be store selected text.