san*_*ay3 63 jquery focus contenteditable
我有一个<div contenteditable=true>
由WYSIWYG定义的一些元素.例如<p>
,<h1>
等等.我想直接关注其中一个元素.
比如说<p id="p_test">
.但似乎focus()
功能不适用于<div>
元素,<p>
元素......
在我的案例中是否有另一种方法来定义焦点?
chr*_*ong 51
老帖子,但没有一个解决方案适合我.我最终想通了:
var div = document.getElementById('contenteditablediv');
setTimeout(function() {
div.focus();
}, 0);
Run Code Online (Sandbox Code Playgroud)
Dim*_*ich 34
在现代浏览器中,您可以使用:
var p = document.getElementById('contentEditableElementId'),
s = window.getSelection(),
r = document.createRange();
r.setStart(p, 0);
r.setEnd(p, 0);
s.removeAllRanges();
s.addRange(r);
Run Code Online (Sandbox Code Playgroud)
但是如果你的元素是空的我有一些奇怪的问题,所以对于空元素,你可以这样做:
var p = document.getElementById('contentEditableElementId'),
s = window.getSelection(),
r = document.createRange();
p.innerHTML = '\u00a0';
r.selectNodeContents(p);
s.removeAllRanges();
s.addRange(r);
document.execCommand('delete', false, null);
Run Code Online (Sandbox Code Playgroud)
删除游标后停留在p元素内
PS只是普通的空间对我不起作用
Vla*_*lad 28
我注意到jQuery focus()不适用于宽度和高度为0的我唯一的DIV.我用.get(0).focus() - 原生的javascript焦点方法替换它 - 它的工作原理.
很多时候如果你不能调用.focus()
一个元素,那是因为 tabIndex 是 -1,这意味着当你按 Tab 键导航时,tab 键不能聚焦在它上面。
将 tabIndex 更改为 >= 0 将使您专注于元素。如果您需要动态执行此操作,只需在事件侦听器中向元素添加 tabindex >= 0 即可。
小智 6
你可以试试这个代码,它可以自动聚焦在你上次插入的位置。
let p = document.getElementById('contenteditablediv')
let s = window.getSelection()
let r = document.createRange()
r.setStart(p, p.childElementCount)
r.setEnd(p, p.childElementCount)
s.removeAllRanges()
s.addRange(r)
Run Code Online (Sandbox Code Playgroud)
进一步建立@Surmon答案。如果您希望在文本中的最后一个字母/数字而不是最后一个插入位置之后自动聚焦(如果子节点包含在块类型标签而不是纯文本中,则最后一个插入位置会将光标移动到新行)然后应用这个小修改:
r.setStart(p.lastChild, 1);
r.setEnd(p.lastChild, 1);
Run Code Online (Sandbox Code Playgroud)
这是一个扩展函数,用于检查编辑器/元素是否有任何子节点,并根据情况在末尾相应地设置光标:
let p = document.getElementById('contenteditablediv');
p.focus(); // alternatively use setTimeout(() => { p.focus(); }, 0);
// this is enough to focus an empty element (at least in Chrome)
if (p.hasChildNodes()) { // if the element is not empty
let s = window.getSelection();
let r = document.createRange();
let e = p.childElementCount > 0 ? p.lastChild : p;
r.setStart(e, 1);
r.setEnd(e, 1);
s.removeAllRanges();
s.addRange(r);
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*son -12
将“click”事件处理程序绑定到 contenteditable div 内的所有元素,并更改单击时的类/样式(即向元素添加“focused”类);
您可以通过添加彩色边框或内部框阴影等样式来向用户标识哪个元素具有焦点。然后,当您想要访问 jQuery 脚本中的焦点元素时,只需执行以下操作:
var focused = $('.focused');