event.preventDefault() is not working in IE 11 for

2019-07-20 14:36发布

I have a polymer element which triggers a custom event synchronously and I want to know whether the event was cancelled using event.preventDefault(). Using event.defaultPrevented I can know the intended action. This works on all browsers(Chrome, Canary, Firefox, Opera) but on IE 11 (not worried about older browsers) its not working. I know I can set some property on my event and check for that back where I am triggering and handle but want to know if there is something else which I missed.

You can try out the code from http://jsbin.com/husamupi/1/edit

2条回答
forever°为你锁心
2楼-- · 2019-07-20 14:40

It looks like IE 11 does not set defaultPrevented for "synthetic" events created by code.

Example JSbin: http://jsbin.com/wohafoyo/1/edit

No matter what I tried in terms of event creation and dispatching, I could not make a synthetic click event's preventDefault set defaultPrevented to true.

Perhaps Polymer could modify CustomElement.prototype.preventDefault to set defaultPrevented.

查看更多
Juvenile、少年°
3楼-- · 2019-07-20 15:02

I had the same problem and could solve it with the following hack:

var event = document.createEvent('CustomEvent');
event.initCustomEvent('custom', true, true, {});
event.preventDefault = function () {
    Object.defineProperty(this, "defaultPrevented", {get: function () {return true;}});
};
event.preventDefault();
event.defaultPrevented; // true
查看更多
登录 后发表回答