英文:
How can I create a custom HTML element with accessibility
问题
无法键盘访问的元素
英文:
How can I create a custom HTML element that can be styled with CSS and have specific behaviors, such as click events, proper semantics, and accessibility? Are there any best practices for defining specific behaviors for custom HTML elements using event listeners? What are some examples of custom HTML elements that have been successfully implemented on websites
<!DOCTYPE html>
<html>
<head>
<title>Custom HTML Element Example</title>
<style>
.custom-element {
background-color: #ccc;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<custom-element >Click me</custom-element>
<script>
class CustomElement extends HTMLElement {
constructor() {
super();
this.addEventListener('click', () => {
alert('You clicked the custom element!');
});
}
}
window.customElements.define('custom-element', CustomElement);
</script>
</body>
</html>
element is not keyboard accessible
答案1
得分: 0
FYI:您的点击只在此处起作用,因为您在DOM中解析<custom-element>
之后定义了组件。默认情况下,在constructor
中没有创建DOM(尝试使用document.createElement("custom-element")
会导致错误)。
connectedCallback
会告诉您元素实际上在DOM中时,那时您可以分配事件。
<!-- 开始代码片段:js 隐藏:false 控制台:true babel:false -->
<!-- 语言:lang-html -->
<style>
.custom-element {
background-color: #ccc;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<custom-element>单击我</custom-element>
<script>
customElements.define('custom-element', class extends HTMLElement {
//constructor() {
//super();
// 仅在此处设置属性或shadowDOM
// 此元素尚未在DOM中!
//}
connectedCallback(){
// 可以在此处执行oldskool内联点击
// 因为(原则上)页面中没有其他代码
// 应该干扰此组件
this.onclick = () => alert("内联点击!");
this.addEventListener('click', () => {
alert('您单击了自定义元素!&39;);
});
}
});
</script>
<!-- 结束代码片段 -->
英文:
FYI: Your click only works here because you defined the component after <custom-element>
was parsed in the DOM. By default there is no DOM created in the constructor
(try a document.createElement("custom-element")
; it will error.
The connectedCallback
tells you when the element is actually in the DOM, and that is when you can assign Events.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<style>
.custom-element {
background-color: #ccc;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<custom-element>Click me</custom-element>
<script>
customElements.define('custom-element', class extends HTMLElement {
//constructor() {
//super();
// only set properties or shadowDOM here
// this element is NOT in the DOM yet!
//}
connectedCallback(){
// might as well do oldskool inline clicks here
// because (in principle) no other code in the page
// should mess with this component
this.onclick = () => alert("inline click!");
this.addEventListener('click', () => {
alert('You clicked the custom element!');
});
}
});
</script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论