javascript - 覆盖绝对定位元素时忽略 mouseleave 事件
问题描述
我有一个表,其中有一堆行,我需要既可编辑又可删除。我制作了一个<div>
包含几个按钮,当行悬停时,我想在相关位置显示这些按钮。这一切都很好。当鼠标离开表格本身时,我还希望按钮消失。好的,我会使用这个mouseleave
事件,我想。不幸的是,当鼠标也进入按钮时,这也会触发<div>
,从而导致按钮不断显示和隐藏的反馈循环。
这很难描述,但希望这是说明性的:https ://jsfiddle.net/8d726rqt/
我确实已经尝试找到答案,并且有很多显示和隐藏的项目是父元素的子元素,但对我而言并非如此,因此这些解决方案不起作用。此外,通常建议使用pointer-events: none
. 这确实有效,但是按钮不会接收点击事件,从而破坏了这一点。
解决方案
#edit-control
不在里面#top-level-table
。因此,当#edit-control
出现并且鼠标在它上面时,它会触发 mouseleave 事件。然后按钮消失,鼠标再次进入表格。因此按钮再次出现。它变成了一个循环,按钮一直显示隐藏。
我建议将 mouseleave 事件添加到 and 的包装器 div#edit-control
中#top-level-table
。
$(function()
{
$('.list-row').mouseover(function()
{
var offset = $(this).offset();
$('#edit-controls').css({
'top': offset.top + 10,
'left': offset.left + 10
}).fadeIn();
//console.log('fadein');
});
//change to this element with mouseleave event
$('#table-wrapper').mouseleave(function()
{
// console.log('fadeout');
$('#edit-controls').fadeOut();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script crossorigin="anonymous" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive" id="table-wrapper">
<table id="top-level-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Table</th>
</tr>
</thead>
<tbody>
<tr class="list-row">
<td>Content<br><br>Things</td>
</tr>
<tr class="list-row">
<td>Content<br><br>Things</td>
</tr>
<tr class="list-row">
<td>Content<br><br>Things</td>
</tr>
<tr class="list-row">
<td>Content<br><br>Things</td>
</tr>
</tbody>
</table>
<div id="edit-controls" style="display:none; position:absolute; z-index:1" >
<button type="button" class="btn btn-primary">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</body>
</html>
推荐阅读
- ruby-on-rails - Rails - LoadError(无法加载此类文件 - json_web_token)
- sql - 避免在 SQL Server 过程中获取
- angular - 效果“AuthEffects.register$”发送了一个无效动作
- javascript - 上传文件时如何在服务器上获取表单数据值?
- clojure - YeSQL:哪个键需要值?
- java - 单击按钮时如何更改按钮颜色
- php - 连接时使用列作为表名
- excel - Outlook VBA 代码未退出
- javascript - Javascript - 过滤偶数
- twig - 带有 Symfony 4 插件的 PhpStorm 中缺少 Twig 模板