简体   繁体   English

在边界外单击时触发带有onclick事件的自定义元素

[英]Custom Element with onclick event fires when clicked outside boundaries

I built a custom element with an onclick eventListener attached to it. 我建立了一个自定义元素,并附加了onclick eventListener。 The width is set by CSS to 200px. CSS将宽度设置为200px。 When I append the custom element to a wider table cell, the eventListener even catches clicks outside the custom element (but inside the table cell). 当我将自定义元素附加到更宽的表格单元格时,eventListener甚至在自定义元素之外(但在表格单元格内)捕获点击。

When exploring the element with the Firefox Inspector it seems that the custom element fills the whole table cell although its width is set. 当使用Firefox Inspector浏览元素时,尽管设置了宽度,但自定义元素似乎填充了整个表格单元。 Why is that happening? 为什么会这样呢?

 class Test extends HTMLElement { constructor() { super(); var shadow = this.attachShadow( { mode: 'open' } ); var f = document.createElement('font'); f.innerHTML = 'text'; var div = document.createElement('div'); div.style.border = '1px solid black'; div.style.width = '200px'; this.addEventListener('click', function() { console.log('clicked'); }); div.appendChild(f); shadow.appendChild(div); } } customElements.define('my-test', Test); 
 <table border=1 style='border-collapse: collapse;'> <tr> <td style='width: 800px;' align='center'> <my-test></my-test> </td> </tr> </table> 

You need to set display: inline-block; margin:0; padding: 0 您需要设置display: inline-block; margin:0; padding: 0 display: inline-block; margin:0; padding: 0 display: inline-block; margin:0; padding: 0 on the :host value to make the host element fit the overall size of the children inside the shadowDOM :host值的display: inline-block; margin:0; padding: 0 ,以使host元素适合shadowDOM内部子元素的整体大小

 class Test extends HTMLElement { constructor() { super(); var shadow = this.attachShadow( { mode: 'open' } ); shadow.innerHTML = `<style> :host { background-color: #F99; border: 1px dashed #900; display: inline-block; margin: 0; padding: 0; } </style>`; var div = document.createElement('div'); div.style.backgroundColor = '#aaa'; div.style.width = '200px'; this.addEventListener('click', function() { console.log('clicked'); }); var f = document.createElement('font'); f.innerHTML = 'text'; div.appendChild(f); shadow.appendChild(div); } } customElements.define('my-test', Test); 
 <table border=1 style='border-collapse: collapse;'> <tr> <td style='width: 800px;' align='center'> <my-test></my-test> </td> </tr> </table> 

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

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