无论您在网页上点击哪个位置,都可以获得焦点。
如何仅在单击自身元素但不在元素外部时才进行焦点?
参见演示: http://jsbin.com/iTEkUKa/1/edit
尝试在任何方框外面点击,它仍会导致焦点,这就是问题所在。
答案 0 :(得分:2)
使用此脚本:
它很容易解释如下:
在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;
}
}