简体   繁体   English

toggleClass / addClass不适用于输入

[英]toggleClass/addClass doesn't work with input

I have an input element: 我有一个输入元素:

<input id="box" type="text" />

And the following CSS class: 以及以下CSS类:

.box-change
{
    border-color:#ffffff;
}

As well as the following jQuery code: 以及以下jQuery代码:

$('#box').toggleClass('box-change');

However, it doesn't change the border color as I expect it to. 但是,它并没有像我期望的那样改变边框颜色。 Does anyone know why? 有人知道为什么吗?

Edit: 编辑:

The input already has a style, it is thus: 输入已经具有样式,因此是:

#box
{
border-color:#ff0000;
border-style:solid;
border-bottom-width:1px;
border-left-width:1px;
border-top-width:1px;
}

If you've originally removed border, then you'll have to set 如果您最初删除了边框,则必须设置

border-width

and

border-style

So in short your CSS should look like: 简而言之,您的CSS应该如下所示:

.box-change
{
    border: 1px solid #fff;
}

But it all depends what your initial style is, what colour is background of the containing element of your input etc... 但这全都取决于您的初始样式是什么,输入的包含元素的背景是什么颜色等...

Edit after you've provided more detail 提供更多详细信息后进行编辑

your class doesn't get applied because class that sets style by ID has higher priority in cascade than CSS class. 您的类无法应用,因为按ID设置样式的类在层叠中的优先级高于CSS类。 That's the main reason why you're not seeing it applied. 这就是为什么您看不到它的主要原因。

If you'd like your CSS class to take over you have two options: 如果您希望CSS类接管您,则有两种选择:

  1. set it as important: 将其设置为重要:

     .box-change { border: 1px solid #fff !important; } 
  2. provide CSS rule that has higher specificity and will take over 提供具有更高特异性的CSS规则,并将接管

     #box.box-change { border: 1px solid #fff; } 

The second way is the preferred way, because using !important will make your CSS harder to maintain, since your classes don't cascade as per CSS but rather as per your importance. 第二种方法是首选方法,因为使用!important会使您的CSS难以维护,因为您的类不是根据CSS而是根据您的重要性进行层叠的。 And you can easily loose control over that. 您可以轻松地对此进行控制。 Avoid important unless on seldom occasions. 除非在极少数情况下,否则避免重要。

How to troubleshoot this? 如何解决这个问题?

To help you in the future, you should be using developer tools in browser (Chrome DevTools or Firebug for Firefox) that would immediately show you the problem. 为了将来为您提供帮助,您应该在浏览器中使用开发人员工具(Chrome DevTools或Firefox的Firebug),该工具会立即向您显示问题。 And of course understand CSS specificity rules and how they cascade. 当然,还要了解CSS专用规则及其级联方式。

As your original styles are defined with #box it is more specific than .box-change , and by default overrides your new additions. 由于原始样式是使用#box定义的,因此比.box-change更具体,并且默认情况下会覆盖您的新样式。 It could also be that .box-change is higher up the cascade than #box . 也可能是.box-change在级别上比#box

You could solve it one of two ways: 您可以通过以下两种方法之一解决它:

#box.box-change{
  border-color: #fff;
}

or 要么

.box-change{
  border-color: #fff !important;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM