CSS选择器比较2个属性 [英] CSS Selector compare 2 attributes
问题描述
我正在寻找一种构建选择器的方法,该选择器将匹配两个属性具有相同值但找不到语法的位置.这可能吗?怎么样?
I'm looking for a way to build a selector that would match where two attributes have the same value, but can't find a syntax. Is this possible? How?
我希望能起作用:
[data-valueA=data-valueB]
当我提前知道valueA和valueB时,我可以这样做:
When I know valueA and valueB ahead of time, I could do:
[data-valueA="knownValueForA"][data-valueB="knownValueForB"] {}
但是我不知道这些值,在这种情况下也不关心它们,只是知道它们何时相同.
But I don't know the values and aren't concerned with them in this case, just knowing when they are the same.
以下是可探索的小提琴: https://jsfiddle.net/rainabba/m49e4e7k/
Here's a fiddle to explore with: https://jsfiddle.net/rainabba/m49e4e7k/
为澄清起见,我正在寻找纯CSS解决方案.
To clarify, I'm looking for a pure CSS solution.
推荐答案
这对于标准CSS是不可能的.
This is not possible with standard CSS.
尽管您没有确切询问在那种情况下,我可以做什么?",单凭这个答案就感觉完全不够,因此,这也是一个jQuery解决方案,可能做到这一点.
Although you hadn't exactly asked "Well in that case, what can I do?", leaving this answer on its own feels completely insufficient, so here's also a jQuery solution for something that might do the trick.
假设您仅在寻找div
,下面的代码将起作用.否则,您可以将jQuery第一行中的选择器编辑为$("div")
Assuming you are looking for div
s only, the code below will work. Otherwise, you can edit the selector in the first line of the jQuery to be something other than $("div")
$("[data-valueA]").each(function() {
$this = $(this);
var firstAttr = $this.data("valuea");
var secondAttr = $this.data("valueb");
if (firstAttr == secondAttr) $this.addClass("redBackground");
});
div {
padding: 20px;
margin: 20px;
border: 1px solid black;
}
.redBackground {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-valueA="MyValue" data-valueB="MyValue">
ValueA and ValueB match
</div>
<div data-valueA="XXX" data-valueB="YYY">
ValueA and ValueB do not match
</div>
这篇关于CSS选择器比较2个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!