简体   繁体   English

禁用HTMLElement上的触发事件

[英]trigger event on disabled HTMLElement

I have a textarea element on which I wan't to fire an event. 我有一个textarea元素,我不想发动事件。 When setting up a listener and the element is disabled I get an inconsistent behavior. 设置侦听器并禁用该元素时,我会得到一个不一致的行为。 Chrome (64.0.3282.186), Safari (11.0.3) and Edge fires the event and everything looks good (as I would expect them to do) but in Firefox (58.0.2) the eventlistener does not fire. Chrome(64.0.3282.186),Safari(11.0.3)和Edge会触发事件,一切看起来都不错(正如我所希望的那样),但在Firefox(58.0.2)中,事件监听器不会触发。 Anyone got any idea on how to solve this without enabling the element? 任何人都知道如何在不启用元素的情况下解决这个问题?

 var eventName = 'bar', element = document.querySelector('#foo'), event = new CustomEvent(eventName, { cancelable: true, bubbles: false, detail: null }); element.addEventListener(eventName, function() { element.value = 'X'; }); element.dispatchEvent(event); 
 <textarea id="foo" disabled="disabled"></textarea> 

Add an HTMLElement method that enables the element, dispatches the event and then disables it again afterwards. 添加一个HTMLElement方法,该方法启用元素,调度事件,然后再次禁用它。

 HTMLElement.prototype.fireEvent = function(e) { const isDisabled = this.hasAttribute('disabled'); this.removeAttribute('disabled'); this.dispatchEvent(e); if (isDisabled) this.setAttribute('disabled', true); }; var eventName = 'bar', element = document.querySelector('#foo'), event = new CustomEvent(eventName, { cancelable: true, bubbles: false, detail: null }); element.addEventListener(eventName, function() { element.value = 'X'; }); element.fireEvent(event) 
 <textarea id="foo" disabled="disabled"></textarea> 

Granted, this modifies the native element which is frowned upon - you can avoid prototype methods and just write a plain old function, ie fireEvent(elem, event) . 当然,这会修改不受欢迎的本机元素 - 您可以避免使用原型方法,只需编写一个普通的旧函数,即fireEvent(elem, event)

I posted an bug to Mozilla on the matter as nothing is mentioned in the w3 spec that the element should not dispatch events when the element is disabled. 我在这个问题上向Mozilla发布了一个错误,因为w3规范中没有提到元素在禁用元素时应该调度事件。

The only thing that is mentioned is that mouse events should not be dispatched. 唯一提到的是不应该发送鼠标事件。 https://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#attr-fe-disabled https://www.w3.org/TR/2011/WD-html5-20110525/association-of-controls-and-forms.html#attr-fe-disabled

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element. 禁用的表单控件必须防止在元素上调度在用户交互任务源上排队的任何单击事件。

The bug can be found here: https://bugzilla.mozilla.org/show_bug.cgi?id=1443148 这个bug可以在这里找到: https//bugzilla.mozilla.org/show_bug.cgi?id = 1443148

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM