简体   繁体   English

如果背景为内联样式,请使用CSS样式元素

[英]Use CSS to style element if background inline styling

consider following HTML and CSS: 考虑使用以下HTML和CSS:

I have the second element background set to red with inline styling. 我使用内联样式将第二个元素背景设置为红色。 How can I style the element with the background:red? 如何使用background:red设置元素的样式? I know I can do :nth-child(2), but it is dynamicly different each time? 我知道我可以做:nth-​​child(2),但是每次都动态不同吗?

<div class="titleBox">
    <button>Click meh!</button>
</div>
<div class="titleBox" style="background:red">
    <button>Click meh!</button>
</div>
<div class="titleBox">
    <button>Click meh!</button>
</div>

.titleBox {
    width:200px;
    height:200px;
    float:left;
    border:1px solid;
    opacity:.5
}

So.. if style="background:red", make the opacity equal 1 所以..如果style =“ background:red”,则使不透明度等于1

thanks! 谢谢! http://jsfiddle.net/kM27C/ http://jsfiddle.net/kM27C/

Just check whether the attribute exists 只需检查属性是否存在

Doesn't work properly in IE, but it does if you just check for the existence of the style attribute: 在IE中无法正常工作,但是如果您仅检查style属性是否存在,它就可以:

.titleBox[style] {

Exact matching attribute selector 精确匹配的属性选择器

Use the attribute selector: 使用属性选择器:

.titleBox[style="background:red"] {

Demo-fiddle ( http://jsfiddle.net/Empgz/ ) works fine for Chrome, but not for IE. Demo-fiddle( http://jsfiddle.net/Empgz/ )在Chrome上工作正常,但在IE上工作不正常。 Apparently IE parsed the style, adds some formatting, and then requires the selector to follow that formatting. 显然,IE解析了样式,添加了一些格式,然后要求选择器遵循该格式。 I inspected the element, saw style="background: red;" 我检查了元素,看到了style="background: red;" (with space and semi-colon), so I tried this, which works in IE: (使用空格和分号),因此我尝试了此方法,该方法在IE中有效:

.titleBox[style="background: red;"] {

So, you could add both to your CSS, so it matches any: 因此,您可以将两者都添加到CSS中,以便与以下任何内容匹配:

.titleBox[style="background:red"],
.titleBox[style="background: red;"] /* For IE */ {
  /* properties go here */
}

It's dirty, of course, but if you cannot change the HTML, you'll sometimes have to do something like this. 当然,它很脏,但是如果您不能更改HTML,则有时必须执行类似的操作。 If you can change your HTML, remove the inline style and change it for a class. 如果可以更改HTML,请删除内联样式并将其更改为类。

More special attribute selector ( starting with or contains ) 更特殊的属性选择器( 包含 开头

There is also the ^= operator, using which you can check whether an attribute starts with a value: 还有一个^=运算符,您可以使用该运算符检查属性是否以值开头

/* Any background setting */
.titleBox[style^=background] {
    opacity:1;
}

Demo: http://jsfiddle.net/g7SZ5/1/ 演示: http//jsfiddle.net/g7SZ5/1/

See also The Skinny on CSS Attribute Selectors on CSS-tricks.com for more of such operators. 有关此类运算符的更多信息,另请参见CSS-tricks.com 上的CSS属性选择器的Skinny

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

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