如果你在ipad上使用contenteditablediv,你会发现blur事件没有注册。
下面的答案提供了一个快速破解。
这个答案的来源如下:https://gist.github.com/shimondoodkin/1081133基本上,我们创建了一个输入元素,它可以正确地注册blur,并将焦点更改为它,然后在contenteditablediv应该模糊的时候对它进行模糊。我已经调整了shimondodkin的解决方案,使其完美工作,正确定位输入元素,这样页面在试图聚焦输入元素时不会突然滚动。
if(/AppleWebKit/([d.]+)/.exec(navigator.userAgent)) {
function getPos(el) {
for (var lx=0, ly=0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent) return {x: lx,y: ly};
}
var refocus_prevtarget = null, inp = ce("input", "", document.body); inp.setAttribute("tabIndex","-1"); inp.style.cssText = "width:1px; height:1px; border:none; margin:0; padding:0; position:fixed";
function refocusContentEditable(e) {
var curelement=getEvtSrc(e);
if(refocus_prevtarget) { // if we have a previous element
// if previous element was contentEditable and the next isn't then:
if(refocus_prevtarget.contentEditable == 'true' && curelement.contentEditable !== 'true') {
var p = getPos(refocus_prevtarget); inp.style.left = p.x; inp.style.top = p.y; // change the position of the input element to near the last elem
inp.focus(); inp.blur(); // set caret focus to input el that handles blur correctly
curelement.focus(); // focus the wanted element
}
}
refocus_prevtarget=curelement;
}
aeh(document.body, "touchend", refocusContentEditable); // add global click handler
}