CSS의 JSON

Joseph Gordon-Levitt
풀어 주다: 2025-03-24 09:10:11
원래의
1012명이 탐색했습니다.

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.

위 내용은 CSS의 JSON의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿