Putting Javascript into CSS

前端 未结 3 714
情话喂你
情话喂你 2020-12-11 18:40

I\'ve been thinking about something. On my forum, there are default CSS codes that the users can choose from. This changes everything from background to text color. I have a

3条回答
  •  孤街浪徒
    2020-12-11 19:39

    I wanted to accomplish the same thing (have variables and some processing logic in CSS) that egged me to develop a couple of standalone tools (one Angular and one V-JS):

    • CjsSS.js is a Vanilla Javascript tool (so no external dependencies) that supports back to IE6.

    • ngCss is an Angular Module+Filter+Factory (aka: plugin) that supports Angular 1.2+ (so back to IE8)

    Both of these tool sets allow you to do this in a STYLE tag or within an external *.css file:

    /*
    
    */
    
    BODY {
        color: /*{{mainColor}}*/;
    }
    

    And this in your on-page style attributes:

    blah

    (or for ngCss)

    blah

    NOTE: In ngCss, you could also do $scope.mainColor in place of var mainColor

    By default, the Javascript is executed in a sandboxed IFRAME, but really it's not any different from how the browser processes your *.js files. Just be sure to author your own CSS and host it on your own server then XSS isn't an issue. But the sandbox provides that much more security and peace of mind.

    CjsSS.js and ngCss fall somewhere in-between the other tools around to accomplish similar tasks:

    • LESS, SASS and Stylus are all Preprocessors only and require you to learn a new language and mangle your CSS. Basically they extended CSS with new language features. All are also limited to plugins developed for each platform while CjsSS.js and ngCss both allow you to include any Javascript library via .

    • AbsurdJS saw the same problems with the Preprocessors and went the exact opposite direction; rather than extending CSS, AbsurdJS created a Javascript library to generate CSS without touching CSS directly.

    CjsSS.js and ngCss took the middle ground; you already know CSS, you already know Javascript, so just let them work together in a simple, intuitive way. CjsSS.js can be run server-side (via Node.js) to preprocess the CSS or both can be run client-side. You can also run in a hybrid fashion where most variables are preprocessed and the remaining are done on the client-side.

提交回复
热议问题