【问题标题】:addClass not working?addClass 不工作?
【发布时间】:2012-01-09 11:03:46
【问题描述】:

为什么 addClass 不起作用?单击具有step 类的 div 时,div 背景和字体颜色应该会改变,但什么都没有发生。

    <html>
    <head><style type="text/css">
    .currentstep {
    background-color:#eeb345; padding:5px; color:#000000; font-size:14px; font-family:Arial;
    }
    #stepcontainer {
    overflow:hidden; width:100%; 
    }
    .step {
    float:right; width:auto; margin-right:2px; background-color:#59758d; padding:5px; color:#FFFFFF; font-size:14px; font-family:Arial; cursor:pointer;
    }
    </style>
    <script type="text/javascript">
$(function(){

    $('.step').live('click',function() {

    $(this).addClass('currentstep');
    $(this).siblings('.step').removeClass('currentstep');

    });
});
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
    </head>
    <body>
     <div id='stepcontainer'><div id='reset'><a>Reset</a></div>
    <div class='step'>Step 3</div><div class='step'>Step 2</div><div class='step'>Step 1</div></div>
    </body></html>

【问题讨论】:

  • 只需将脚本 src 放在 jquery 代码上方即可。
  • currentstep 在类 step 之前指定,因此 step 的规则优先。更改样式表中的顺序(这就是 层叠 样式表应该工作的方式)。

标签: javascript jquery html


【解决方案1】:

您将.step.currentstep 应用于同一个div(我假设您不想从div 中删除.step)。来自.stepbackground-color 是第一个,所以这就是坚持的颜色。

尝试将 .currentstep 的 CSS 定义更改为:

.currentstep
{
    background-color:#eeb345 !important;
    padding:5px;
    color:#000000;
    font-size:14px;
    font-family:Arial;
}

这里运行正常:http://jsfiddle.net/tomtheman5/j6f6w/

【讨论】:

  • 在样式表中指定类的顺序很重要——后面的规则优先于前面的规则。 step 放置在样式表中的 currentStep 之后,因此其背景颜色优先,无论类添加到元素的顺序或它们在元素的类值中的位置如何.
猜你喜欢
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多