我可以在 Shadow DOM 中获得一个按钮来提交不在 Shadow DOM 中的表单吗? [英] Can I get a button in Shadow DOM to submit a form not in Shadow DOM?
问题描述
我刚刚遇到了一个有趣的情况,我在本地自定义元素的 Shadow DOM 中有一个提交 ,该元素放置在
中>.
I just ran into an interesting situation where I have a submit <button>
inside the Shadow DOM of a native custom element that is placed inside a <form>
.
<form id="one" action="" method="get">
<s-button>Select</s-button>
#shadow-root
<button>...</button>
<button>Outside</button>
</form>
我还有一个 作为
的直接子元素.
I also have a <button>
as a direct child of the <form>
.
子 导致表单提交.
但是 shadow-root 中的 没有.
But the <button>
in the shadow-root does not.
在某种程度上,我认为这是有道理的.但是有没有人想出一种方法来告诉 shadow-root 与
一起正常工作,或者这是我必须处理的事情JS?
In a way I guess this makes sense. But has anyone figured out a way to tell the shadow-root <button>
to work correctly with the <form>
or is this something I will have to handle through JS?
我知道在 Shadow DOM 层阻止了点击事件,但我很惊讶没有办法让按钮仍然是表单的一部分,可以通过属性或属性设置的东西.
I know click events are blocked at the Shadow DOM layer, but I am surprised that there is no way to allow the button to still be a part of the form, something that can be set up through an attribute or a property.
当然,我可以捕获点击事件,然后从 this
发送一个新的事件,但这不会做同样的事情,因为我的事件将不再由用户生成,并且有大量规则与此相关.
Sure I can capture the click event and then send a new one from this
but that does not do the same thing since my event will no longer be user generated and there are a huge set of rules associated with that.
推荐答案
无论如何你都必须通过 Javascript 来处理它.
You'll have to handle it through Javascript anyway.
一个简单的解决方案是在 light DOM 中添加一个(屏蔽的),并将
click
事件传递给它.
A simple solution is to add a (masked) <button>
in the light DOM, and transfer the click
event to it.
customElements.define( 's-button', class extends HTMLElement {
connectedCallback() {
this.attachShadow( {mode: 'open'})
.innerHTML = `<button>In Shadow</button>`
var submit = this.appendChild( document.createElement( 'button' ) )
this.onclick = () => submit.click()
}
} )
<form onsubmit="console.log('submitted');return false">
<s-button>Select</s-button>
<button>Outside</button>
</form>
这篇关于我可以在 Shadow DOM 中获得一个按钮来提交不在 Shadow DOM 中的表单吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!