gpt4 book ai didi

css - 单击元素时仅关注 contenteditable?

转载 作者:行者123 更新时间:2023-11-28 00:05:17 25 4
gpt4 key购买 nike

似乎有了 contenteditable,无论您在页面上单击什么地方,您都会获得焦点。

如何仅在单击元素本身而不是元​​素外部时才使其成为焦点?

查看演示: http://jsbin.com/iTEkUKa/1/edit

尝试在任何框外单击,它仍然会导致焦点,这就是问题所在。

最佳答案

使用这个脚本:

它的工作原理很容易解释:

在 contenteditable-element 外部单击时获取将聚焦的 contenteditable-element。
如果在接下来的焦点事件中,此元素获得焦点,则将其移除。

https://gist.github.com/nuxodin/b02064610abf93dab8c6

if (/AppleWebKit\/([\d.]+)/.exec(navigator.userAgent)) {
document.addEventListener('DOMContentLoaded', function(){
var fixEl = document.createElement('input');
fixEl.style.cssText = 'width:1px;height:1px;border:none;margin:0;padding:0; position:fixed; top:0; left:0';
fixEl.tabIndex = -1;

var shouldNotFocus = null;

function checkMouseEvent(e){
if (e.target.isContentEditable) return;
var range = document.caretRangeFromPoint(e.clientX, e.clientY);
var wouldFocus = getContentEditableRoot(range.commonAncestorContainer);
if (!wouldFocus || wouldFocus.contains(e.target)) return;
shouldNotFocus = wouldFocus;
setTimeout(function(){
shouldNotFocus = null;
});
if (e.type === 'mousedown') {
document.addEventListener('mousemove', checkMouseEvent, false);
}
}
document.addEventListener('mousedown', checkMouseEvent, false);
document.addEventListener('mouseup', function(){
document.removeEventListener('mousemove', checkMouseEvent, false);
}, false);

document.addEventListener('focus', function(e){
if (e.target !== shouldNotFocus) return;
if (!e.target.isContentEditable) return;
document.body.appendChild(fixEl);
fixEl.focus();
fixEl.setSelectionRange(0,0);
document.body.removeChild(fixEl);
}, true);

});
}
function getContentEditableRoot(el) {
if (el.nodeType === 3) el = el.parentNode;
if (!el.isContentEditable) return false;
while (el) {
var next = el.parentNode;
if (next.isContentEditable) {
el = next;
continue
}
return el;
}
}

关于css - 单击元素时仅关注 contenteditable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18833017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com