我有这个javascript代码:
initializeEventHandlers: function() {
if ( typeof document.implementation != "undefined" &&
document.implementation.hasFeature("HTML", "1.0") &&
document.implementation.hasFeature("Events", "2.0") &&
document.implementation.hasFeature("CSS", "2.0") ) {
document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false);
document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false);
}
else {
document.attachEvent( "onmouseup", this._mouseUpHandler.bindAsEventListener(this) );
document.attachEvent( "onmousemove", this._mouseMoveHandler.bindAsEventListener(this) );
}
}
这适用于大多数浏览器,但是当我使用IE11时它失败了。我知道这是因为IE11删除了对attachEvent的支持,而IE11则落入了else条件。我也看到hasFeature已被弃用,所以我不确定如何最好地检测addEventListner支持。
答案 0 :(得分:1)
以下代码适用于IE11和Firefox,但是它适用于其他/旧浏览器吗?
initializeEventHandlers: function() {
if (document.addEventListener) {
document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false);
document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false);
}
else if (document.attachEvent) {
document.attachEvent( "onmouseup", this._mouseUpHandler.bindAsEventListener(this) );
document.attachEvent( "onmousemove", this._mouseMoveHandler.bindAsEventListener(this) );
}
}
答案 1 :(得分:0)
查看文档是否接受该方法的可靠,可靠的方法是使用“ try {...} catch(err){...}”构造:
const initializeEventHandlers = () => {
try {
if (document.addEventListener) {
document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false);
document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false);
}
else if (document.attachEvent) {
document.attachEvent( "onmouseup", this._mouseUpHandler.bindAsEventListener(this) );
document.attachEvent( "onmousemove", this._mouseMoveHandler.bindAsEventListener(this) );
}
}
catch(err) {
console.info('Error', err );
}
}