[英]Placing cursor and focus inside contenteditable div onclick
当您单击我的td
时,隐藏的 div 将显示在其顶部,并且 div 将变为contenteditable
但我希望鼠标 cursor 出现在其中,因此单击后我可以开始输入。 目前您需要单击两次——一次聚焦,然后再次放置 cursor。
请不要担心我为什么要这样做,我只是将我的代码剥离到基本要素以隔离这个问题。
$(document).ready(function() { $("td").on("mousedown", function() { var cellOffset = $(this).offset(); $('#cellSelect').offset({ top:cellOffset.top-1, left:cellOffset.left-1 }); $('#cellSelect').show(0); $('#cellSelect').attr('contenteditable','true'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div id="cellSelect" style="display:none;position:absolute;border: 2px solid blue;width:91px;height:91px"></div> <table border="1" cellpadding="10" width="100" height="100"> <tr> <td id="1-1"></td> </tr> </table>
调用focus
在元素上。
您需要将focus
调用包装在setTimeout
中,以确保该元素在聚焦之前是可编辑的,否则您将无法输入。
$(document).ready(function() { $("td").on("mousedown", function() { var cellOffset = $(this).offset(); $('#cellSelect').offset({ top:cellOffset.top-1, left:cellOffset.left-1 }); $('#cellSelect').show(0); $('#cellSelect').attr('contenteditable','true'); setTimeout(() => $('#cellSelect').focus(), 0) }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div id="cellSelect" style="display:none;position:absolute;border: 2px solid blue;width:91px;height:91px"></div> <table border="1" cellpadding="10" width="100" height="100"> <tr> <td id="1-1"></td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.