mor*_*kro 1 html javascript web-component custom-events shadow-dom
我正在使用Web Components并尝试将click事件绑定到Shadow DOM内部的元素.
1. component.html包含<link rel="import" ...>在index.html内部
<template id="my-element">
<section>
<header>
<content select="h1"></content>
<button></button>
</header>
<content select="div"></content>
</section>
</template>
Run Code Online (Sandbox Code Playgroud)
2.后期元素用法:
<my-element>
<h1>Headline</h1>
<div>...</div>
</my-element>
Run Code Online (Sandbox Code Playgroud)
3.访问元素并将函数绑定到它
现在我想在我的内部添加一个(不幸的是隐藏了).喜欢:addEventListener()<button><my-element> #shadow-root
var elemBtn = document.querySelector('my-element button');
elemBtn.addEventListener('click', function(event) {
// do stuff
});
Run Code Online (Sandbox Code Playgroud)
但那不行.我如何实现这一目标?
您应该能够在不涉及窗口对象的情况下执行此操作.这是一个完整的例子:
<!-- Define element template -->
<template>
<h1>Hello World</h1>
<button id="btn">Click me</button>
</template>
<!-- Create custom element definition -->
<script>
var tmpl = document.querySelector('template');
var WidgetProto = Object.create(HTMLElement.prototype);
WidgetProto.createdCallback = function() {
var root = this.createShadowRoot();
root.appendChild(document.importNode(tmpl.content, true));
// Grab a reference to the button in the shadow root
var btn = root.querySelector('#btn');
// Handle the button's click event
btn.addEventListener('click', this.fireBtn.bind(this));
};
// Dispatch a custom event when the button is clicked
WidgetProto.fireBtn = function() {
this.dispatchEvent(new Event('btn-clicked'));
};
var Widget = document.registerElement('my-widget', {
prototype: WidgetProto
});
</script>
<!-- Use the element -->
<my-widget></my-widget>
<!-- Listen for its click event -->
<script>
var widget = document.querySelector('my-widget');
widget.addEventListener('btn-clicked', function() {
alert('the button was clicked');
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1496 次 |
| 最近记录: |