在 Javascript 中捕获点击和击键事件,覆盖默认行为?
我使用 jQuery 编写了一些 JavaScript 代码,用于侦听用户在按住或不按住 Shift 键的情况下在页面的不同部分上单击鼠标的情况。
我的页面上有一张表格。这个想法是用户可以通过单击来选择表中的行。用户可以通过单击一行、按住 Shift 键并单击另一行来选择多行。 (这就是用户期望选择多行的方式,但按住 Shift 键,对吗?)
无论如何,我的代码可以在 Internet Explorer 中运行,但我有一个问题。我的代码读取用户的选择,但浏览器同时突出显示两个鼠标单击位置之间的文本。
我怎样才能使我的代码可以根据用户点击选择行并且浏览器不选择文本?
更新我尝试了以下代码:$('tr').bind('mousedown',function() { return false; } );
在我的页面中使用此代码,当我单击一行时,按住 Shift 并单击另一行,两行之间的文本突出显示。这就是我试图压制的。请注意,在我释放鼠标按钮之前,文本会突出显示。
更新#2我尝试了以下代码:
$('tr').bind('mousedown',function(e) {
e.preventDefault();
return false;
});
不幸的是,这似乎根本没有做任何事情。
I've written some JavaScript code using jQuery that listens for the user to click the mouse on different parts of my page with and without holding down the shift key.
I have a table on my page. The idea is that the user can select rows in the table by clicking on them. The user can select multiple rows by clicking one row, holding down shift, and clicking another row. (This is how the user expects to select multiple rows, but holding down the shift key, right?)
Anyways, my code works in Internet Explorer, but I have a problem. My code reads the users selection, but the browser simultaneously highlights the text between the two mouse click locations.
How can I make it so that my code can select the rows based on the user clicks and the browser doesn't select the text?
Update I tried the following code:$('tr').bind('mousedown',function() { return false; } );
With this code in my page, when I click one row, hold down shift and click another row, the text between the two rows is highlighted. This is what I'm trying to suppress. Please note that the text highlights before I release the mouse button.
Update #2 I tried the following code:
$('tr').bind('mousedown',function(e) {
e.preventDefault();
return false;
});
Unfortunately, this doesn't seem to do anything at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是您要抑制的 mousedown 事件。
看看 event.stopPropogation() 和 event.preventDefault()。
It's the mousedown event you want to suppress.
Have a look at event.stopPropogation() and event.preventDefault().
事件处理程序的返回值被规范忽略(jQuery 可能会忽略其他内容)。
您可能正在寻找
preventDefault
和returnValue
(后者的发明正是因为处理程序的返回值被忽略)。您可能还想查看 CSS3 属性扩展
-moz-user-select: none
。The return value of an event handler is ignored by specification (jQuery might to additional stuff).
You may be looking for
preventDefault
andreturnValue
(this latter one was invented precisely because the return value of a handler is ignored).You may also want to look into the CSS3 property extension
-moz-user-select: none
.试试这个
Try this