javascript - Contenteditable 事件 - Jquery
问题描述
我在表格中添加了 contenteditable 道具。我通过使用 keydown 事件获取数据,当用户点击“Enter”时,它会接受新的输入并模糊该区域。但用户也可以点击输入区域以外的任何地方进行模糊。(这是可编辑的功能)。我不能听这个动作。如何为此操作创建事件侦听器,例如 keydown。
这适用于“输入”,但不能点击
<html>
<head></head>
<body>
<table id="table">
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
<tr>
<th>#1</th>
<td contenteditable="true">Editable1</td>
<td contenteditable="true">Editable2</td>
</tr>
</tbody>
</table>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
</body>
</html>
$('#table tbody tr').keydown(function (event){
enter = event.which == 13,
el = event.target;
if(enter){
el.blur();
console.log("entered");
console.log($(this).find(':nth-child(2)').html());
console.log($(this).find(':nth-child(3)').html());
}
});
解决方案
有很多方法可以做到这一点,我想到的一种方法是全局监听 mousedown 事件,并据此决定要做什么,因为鼠标在模糊之前触发:FIDDLE
如果您在红色方块上,则不会发生模糊。
!function(){
//set a variable to listen to
var blur = true;
//your original keydown
document.getElementById("some").addEventListener("keydown",function(e){
if(e.which === 13){
e.currentTarget.blur();
console.log("entered");
}
},false);
//add a blur listener to modify, e.preventDefault won't work
document.getElementById("some").addEventListener("blur",function(e){
//decide what to do based on this variable
if(!blur){
e.currentTarget.focus();
}
},false);
//listen globally to click events, and set blur variable based on a condiditon
window.addEventListener("mousedown",function(e){
if(!document.activeElement){return};
//a condition, if we are on red square, blur won't take place
if(
document.elementFromPoint(e.clientX,e.clientY) === document.getElementById("some2")
){
blur = false;
} else {
blur = true;
}
},false);
}()
推荐阅读
- java - Raspberry pi 2 B + Selenium Java = WebDriverException: java.net.ConnectException: Failed to connect
- javascript - 使用 cron 间隔将数据保存到数据库
- java - Maven 不能使用作用域编译
- excel - 如何将带有格式的excel表格复制到word中 - 手动操作
- r - 使用 R 中的 group_by 函数按位置调用数据框的列
- google-colaboratory - 如何在 Google Colab 中导入和运行 SQL 查询?
- pandas - 在数据框中查找字符串的索引和列号
- javascript - 如何从 MongoDB 中的数组中渲染对象并做出反应
- ios - 无法从 Firebase 中注销帐户
- python - pystray 与其他代码执行