我在 Firefox 中使用 addEventListener
时遇到一些问题。
我的网站上有一个 iframe,用于我自己构建的所见即所得区域。
我希望 iframe 看起来更像普通的文本区域,所以我希望 iframe 周围有一个焦点边框。第一个 tp (textpreview) 是这样找到的(并且效果很好):
var tp = document.getElementById('iframe-textpreview');
var iframe = tp;
if(tp.contentDocument){ // normal
tp = tp.contentDocument;
}
else if(tp.contentWindow){ // old IE
tp = tp.contentWindow.document;
}
//Open and close for Firefox
tp.open();
tp.close();
tp.designMode = 'on';
然后我尝试附加一个事件监听器
并在事件触发时进行记录。这适用于 Chrome、Opera 和最新的 IE,但不适用于 Firefox:
//Doesn't work in Firefox
tp.body.addEventListener('focus', function(){ console.log('focus...')});
tp.body.addEventListener('blur', function(){ console.log('blur...')});
但是这确实有效:
//Firefox
tp.body.onfocus = function(){ console.log('focus...')};
tp.body.onblur = function(){ console.log('blur...')};
我已经清除了 Firefox 上的缓存并尝试使用另一台计算机,但仍然无法使第一个选项正常工作。
最佳答案
出于某种原因,Firefox 不会在 body 元素上触发事件处理程序,而是您必须将事件处理程序附加到 iframe 本身或 iframe 内的实际元素。
专注于 iframe 本身,而不是正文,似乎适用于所有浏览器
tp.addEventListener('focus', function(){ console.log('focus...')});
tp.addEventListener('blur', function(){ console.log('blur...')});
关于javascript - Firefox element.event 有效,但 element.addEventlistener 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20858541/