Last active
October 24, 2023 01:50
-
-
Save nexpr/9db3fd84a653ef95947b6b241600aaff to your computer and use it in GitHub Desktop.
LitElement で直接 CSS を書けるようにする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { html } from "lit" | |
import { StylitElement } from "./StylitElement.js" | |
customElements.define("foo-bar", class extends StylitElement { | |
static properties = { | |
name: {}, | |
} | |
constructor() { | |
super() | |
this.name = "" | |
} | |
render() { | |
return html` | |
<div class=${this.style`display: flex; flex-flow: column; gap: 10px;`}> | |
<div | |
class=${this.style` | |
border: 2px solid #aaa; | |
padding: 12px; | |
:is(input) { | |
padding: 4px; | |
} | |
`} | |
> | |
<label>name</label> | |
<input .value=${this.name} @input=${event => this.name = event.target.value}> | |
</div> | |
<div | |
class=${this.style` | |
border: 2px solid #f8d; | |
padding: 20px; | |
:is(input) { | |
padding: 4px; | |
} | |
`} | |
> | |
<label>name</label> | |
<input .value=${this.name} @input=${event => this.name = event.target.value}> | |
</div> | |
${["#f00", "#0f0", "#00f"].map(color => { | |
return html` | |
<div | |
class=${this.style` | |
border: 2px solid ${color}; | |
padding: 12px; | |
:is(input) { | |
padding: 4px; | |
} | |
`} | |
> | |
<label>name</label> | |
<input .value=${this.name} @input=${event => this.name = event.target.value}> | |
</div> | |
` | |
})} | |
</div> | |
` | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LitElement } from "lit" | |
export class StylitElement extends LitElement { | |
constructor() { | |
super() | |
this._cssss = new CSSStyleSheet() | |
this._style_num = 0 | |
} | |
style(template, ...values) { | |
const class_name = "c" + (this._style_num++).toString(36) | |
this._cssss.insertRule(`.${class_name} {${String.raw(template, ...values)}}`) | |
return class_name | |
} | |
update() { | |
this._style_num = 0 | |
const old = this._cssss | |
this._cssss = new CSSStyleSheet() | |
super.update() | |
const index = this.shadowRoot.adoptedStyleSheets.indexOf(old) | |
if (index < 0) { | |
this.shadowRoot.adoptedStyleSheets.push(this._cssss) | |
} else { | |
this.shadowRoot.adoptedStyleSheets.splice(index, 1, this._cssss) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment