我创建了一个自定义元素:
const templ = document.createElement('template');
templ.innerHTML = `
<span><slot></slot></span>
`;
class SlideButton extends HTMLElement {
constructor() {
super();
// Attach a shadow root to the element.
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(tmpl.content.cloneNode(true));
this.span = shadowRoot.querySelector('span');
this.triggerEvent = new CustomEvent("trigger", {
bubbles: false,
cancelable: false,
});
this.initMouseEvents();
}
initMouseEvents() {
this.span.addEventListener('mousedown', (e) => {
//Watch and calculate slide amount..
this.addEventListener('mousemove', this.slide, false);
});
//When button is released...
document.addEventListener('mouseup', handleMouseUp = (e) => {
this.removeEventListener('mousemove', this.slide, false);
document.removeEventListener('mouseup', handleMouseUp);
//If slided enough, dispatch event...
if (Math.abs(this.slideAmount) > (this.maxSlide * 0.75)) {
console.log('firing event');
this.dispatchEvent(this.triggerEvent);
}
//Reset button to normal state...
}, false);
}
}
在我的代码中的其他位置...
class SpotLightModal {
//Constructor..
//code..
//code..
init() {
this.actions.querySelector('slide-button[type="den"]').addEventListener('trigger', e => {
console.log(e);
console.log('den');
//Do stuff..
});
}
//code...
//code...
}
除了事件监听器中回调运行两次并输出以下内容外,一切均按预期工作:
firing event
CustomEvent {...}
den
CustomEvent {...}
den
e.stopPropagation()
和 e.preventDefault()
都没有效果,尝试使用它们也无济于事。
我已经编辑了文本以包括 this.span
,并将 "mouseup" 事件监听器移动到 "mousedown" 事件监听器之外,但这没用,实际上,现在记录 this
时,会给出另一个不同的元素(同一类型的 <slide-button>
,页面上的第一个), "mouseover" 监听器没有被移除,并且事件也没有被触发。
我在这里做错了什么?或者我缺少了什么?
提前致谢。