最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set a background color defined as a CSS class (using JQuery eventually)? - Stack Overflow

programmeradmin0浏览0评论

I am still new to CSS/Javascript/JQuery. I am defining a couple of colors as classes in a css file. Then, I want to use one of them as the background color of a HTML page:

.wf_blue { color:rgb(2, 12, 40); }
.wf_white { color:rgb(255, 252, 247); }

body{background-color: wf_blue;}

The above does not work. I tried with JQuery, but unsuccessfully. I have seen other questions on SO, but could not figure out the solution. What am I doing wrong?

I am still new to CSS/Javascript/JQuery. I am defining a couple of colors as classes in a css file. Then, I want to use one of them as the background color of a HTML page:

.wf_blue { color:rgb(2, 12, 40); }
.wf_white { color:rgb(255, 252, 247); }

body{background-color: wf_blue;}

The above does not work. I tried with JQuery, but unsuccessfully. I have seen other questions on SO, but could not figure out the solution. What am I doing wrong?

Share Improve this question edited Oct 22, 2011 at 21:00 meo 31.3k19 gold badges89 silver badges123 bronze badges asked Oct 22, 2011 at 20:55 Jérôme VerstryngeJérôme Verstrynge 59.7k96 gold badges295 silver badges466 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

your classes can only be used in the HTML markup like this

<body class="wf_blue">....

Alternative you can set this class with jQuery

$('body').addClass('wf_blue');

If you would like to use variables in CSS, you can take a look at SASS or LESS, which are CSS preprocessors

If you want to use variables in CSS, then you have to use an intermediate language, like less or Sass.

First, the CSS should be:

.wf_blue { background-color: rgb(2, 12, 40); }
.wf_white { background-color: rgb(255, 252, 247); }

In plain HTML

<body class="wf_blue">

With jQuery:

$(document).ready(function() {
  $("body").addClass("wf_blue");
});

If you do not want to use a javascript library (such as jquery or prototype), you can write directly: A. HTML:

 <body class="wf_blue">

B. javascript:

 document.getElementsByTagName ('body') [0]. addClass ('wf_blue');

thanks

发布评论

评论列表(0)

  1. 暂无评论