高级CSS选择器 - 基于样式选择 [英] Advanced CSS Selector - Select based on styling

查看:117
本文介绍了高级CSS选择器 - 基于样式选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了性能问题之外,是否可以使用样式作为选择器?例如:

Performance issues aside, is it possible to use a style as a selector? For example, something like:

div[background-image="img/someimg.jpg"] {opacity:.5}

我的备用计划是使用javascript并迭代div(在找到时添加类)

My fallback plan is to use javascript and iterate over divs (adding a class when found), but this might end up being even more expensive given that the page is highly dynamic, and I'm not in control of the divs being added.

推荐答案

属性W3C页面


CSS 2.1允许作者指定符合在源文档中定义的某些属性的元素的规则。

CSS 2.1 allows authors to specify rules that match elements which have certain attributes defined in the source document.

属性是从HTML代码本身定义的东西,例如 id class src href 等:

Attributes are the things defined from the HTML code itself, like id, class, src, href, etc.:

<a id="foo" href="bar">Foo</a>



c>属性,像这样:

Unless you specifically defined the style from within a style attribute, like this:

<div style="background-image: url('img/someimg.jpg');">Foo</div>

您无法对CSS执行任何操作。

You can't do anything with CSS.

如果您做了内联,您可以尝试此选择器:

If you did do it inline, you could try this selector:

div[style="background-image: url('img/someimg.jpg');"]
{
  /* ... */
}

现在您担心性能问题,您可以尝试使用纯JS来执行此操作(未测试):

Now that you're worried about performance, you can try using pure-JS to do this (untested):

var divs = document.getElementsByTagName('div');

for (var i = 0; i < divs.length; i++)
{
  var current = divs[i];

  if (current.style.backgroundImage == "url('img/someimg.jpg')")
  {
    current.style.opacity = 0.5; // You'll need more hacks for IE...
  }
}

这篇关于高级CSS选择器 - 基于样式选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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