Rumah > hujung hadapan web > tutorial css > JSON dalam CSS

JSON dalam CSS

Joseph Gordon-Levitt
Lepaskan: 2025-03-24 09:10:11
asal
1012 orang telah melayarinya

JSON in CSS

Jonathan Neal tweeted a heck of a little CSS trick the other day, putting JSON inside CSS and plucking it out with JavaScript. Valid values for custom properties are quite liberal! So this looks for a CSS rule (e.g. a whole block, like #x { y: z; } where the cssText starts with -- (which is not a valid selector, but who cares — you could change it if you want to thisIsJson or something) and then slices out a string that JSON.parse() works on.

I re-typed his example here:

Is this useful?

WELL.

Probably not, like, on a daily basis. But remember that JSONP is still a thing because CORS exists. Chucking some JSON in CSS I would think is another way around CORS. I kinda doubt it will catch on, but it’s possible. Remember not long ago we were talking about using CSS as an API for literal data. Another questionable idea. ;)

I think “putting weird stuff in custom properties” is the new “putting weird stuff in CSS content.”

For example, ya know how there are media queries in JavaScript, à la matchMedia? And, of course, there are media queries in CSS, too. There was a time (and I’m not sure it’s passed) where defining those media queries only once felt like a good idea, so we weren’t maintaining media queries in multiple places. To keep them “in sync” one idea was to define them in CSS and have them swap the value of some CSS content (e.g. @media (max-width: 500px) { body::after { content: "max500"; display: none; } }) then literally watch for that content to change with JavaScript — and you’d know that media query was active. For real! No joke!

And speaking of JSON in CSS, you can chuck straight-up JavaScript in there as well. This isn’t as clever as Jonathan’s extraction because it just yanks the value out and evals it.

Caleb Williams made a Web Worker with CSS.

Atas ialah kandungan terperinci JSON dalam CSS. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan