vvcomponent
Version:
VV组件
64 lines (59 loc) • 1.92 kB
JavaScript
class aSwitch extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.isChecked = false;
}
connectedCallback() {
this.render();
this.addEventListeners();
}
addEventListeners() {
this.shadowRoot.querySelector(".switch").addEventListener("click", () => {
this.isChecked = !this.isChecked;
this.updateSwitch();
});
}
updateSwitch() {
const switchElement = this.shadowRoot.querySelector(".switch");
if (this.isChecked) {
switchElement.classList.add("checked");
} else {
switchElement.classList.remove("checked");
}
}
render() {
this.shadowRoot.innerHTML = `
<style>
.switch {
width: 50px;
height: 25px;
background-color: #d3d3d3;
border-radius: 25px;
position: relative;
cursor: pointer;
transition: background-color 0.3s ease;
}
.switch::before {
content: "";
width: 21px;
height: 21px;
background-color: white;
border-radius: 50%;
position: absolute;
top: 2px;
left: 2px;
transition: transform 0.3s ease;
}
.switch.checked {
background-color: #007bff;
}
.switch.checked::before {
transform: translateX(25px);
}
</style>
<div class="switch"></div>
`;
}
}
customElements.define("iftc-switch", aSwitch);