如何动态更改背景颜色html? [英] How can I dynamically change the background-color html?

查看:981
本文介绍了如何动态更改背景颜色html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改HTML或正文的背景(渐变)以响应事件。是否可以使用jQuery更改background-color属性?或者(我有CSS类*中描述的背景渐变)我需要removeClass然后addClass?如果后者,我有一个轻微的困境:我要使用三种不同的颜色。我需要通过removeClass删除两个其他颜色(即使,显然,只有一个将被激活),或有一种方法来编程确定哪一个当前正在使用,只是删除?我想我可以在ready函数的顶部使用一个全局var来跟踪它,但是有更好/更优雅的方式吗?

I want to change the background (gradient) of either the html or body in response to an event. Is it possible to change the background-color attribute using jQuery? Or (I have the background gradients described in CSS classes*) do I need to removeClass then addClass? If the latter, I have a slight dilemma: I am going to use three different colors. Do I need to remove both of the other colors via removeClass (even though, obviously, only one will be active), or is there a way to programmatically determine which one is currently in use and just remove that? I reckon I could use a global var atop the ready function to keep track of that, but is there a better/more elegant way?

.silverBackground {
    background: #e2e2e2; /* Old browsers */
    background: -moz-linear-gradient(top, #e2e2e2 0%, #dbdbdb 50%, #d1d1d1 51%, #fefefe 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e2e2e2), color-stop(50%,#dbdbdb), color-stop(51%,#d1d1d1), color-stop(100%,#fefefe)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* IE10+ */
    background: linear-gradient(to bottom, #e2e2e2 0%,#dbdbdb 50%,#d1d1d1 51%,#fefefe 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e2e2e2', endColorstr='#fefefe',GradientType=0 ); /* IE6-9 */
}


推荐答案

这是我会做的

$('someElement').click(function(){ // 1
   var newClass = $(this).attr('toggleColor'); // 2
   $(document.body).removeClass('color1 color2 color3').addClass(newClass); // 3
});

-----详情------

----- Details ------


步骤



steps


  1. 向元素添加一个点击事件, / li>
  2. 获取新的类名,假设您将在元素的属性中使用此名称

  3. 从元素中删除每个颜色类,然后添加新


这篇关于如何动态更改背景颜色html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆