Javascript - 鼠标事件和浮动元素问题
我使用 jQuery 编写的脚本遇到了一个棘手的问题。
我有一个表格,如果将鼠标悬停在该表格上(标题行除外),该表格的任何行上都会出现一个工具栏。这非常有效,这是它的代码:
$cont.delegate('tr:not(:eq(0))','mouseover mouseout', function(e){
var $this = $(this);
var pos = $this.position();
if(e.type == 'mouseout') {
$actionToolbar.hide();
} else {
$actionToolbar.css({
'top' : pos.top + $this.height()/2 - $actionToolbar.height()/2,
'left' : pos.left + $this.width() - $actionToolbar.width()
}).show();
}
});
当我将鼠标悬停在操作工具栏上时,就会出现问题。该行的 mouseout
事件触发,工具栏隐藏(然后进入显示/隐藏的无限循环)。这是因为工具栏是绝对定位的,而不是该行的子项。
事情是这样的:
- 我不希望它成为该行的子级,因为这意味着我必须为每个鼠标事件删除并附加到 DOM - 而这效率不高就像简单地更新元素的 CSS 一样。
- 如果可能的话,我还想避免计时器来解决这个问题。
提前致谢!
I've got a tricky problem with a script I'm writing using jQuery.
I have a table which will have a toolbar appear on any row if hovered over (except the heading row). This is working great, and this is the code for it:
$cont.delegate('tr:not(:eq(0))','mouseover mouseout', function(e){
var $this = $(this);
var pos = $this.position();
if(e.type == 'mouseout') {
$actionToolbar.hide();
} else {
$actionToolbar.css({
'top' : pos.top + $this.height()/2 - $actionToolbar.height()/2,
'left' : pos.left + $this.width() - $actionToolbar.width()
}).show();
}
});
The problem arises when I hover over the action toolbar. The row's mouseout
event fires, and the toolbar hides (then enters an infinite loop of showing/hiding). This is because the toolbar is absolutely positioned and not a child of the row.
Here's the deal:
- I do not want it to be a child of the row, because that means I'd have to remove and append to the DOM for every mouse event -- and this is not as efficient as simply updating the element's CSS.
- I would also like to avoid timers to solve this if possible.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于缺乏耐心,我找到了自己的答案:
我删除了 mouseout 事件侦听器,转而使用 jQuery 的 data() 方法来跟踪先前悬停的行。然后,我向容器添加一个
mouseleave
事件侦听器。它工作完美:
Having little patience, I've gone and found my own answer:
I've removed the
mouseout
event listener and moved to using jQuery'sdata()
method to keep track of the previously hovered row. Then, I add amouseleave
event listener to the container.It works perfectly:
尝试使用 mouseenter 和 mouseleave,而不是 mouseover 和 mouseout。
Try mouseenter and mouseleave instead of mouseover and mouseout.
将标记 css 选择器放在操作工具栏上,并使用 jquery 检查它。如果您的事件目标具有该标记选择器,则请勿应用。
Put a marker css selector on your action toolbar and check for it using jquery. Then don't apply if your event's target has that marker selector.