我需要给特定的跨度一个特定的颜色,但只有当它的前一个兄弟有“显示: block ”时。我无法直接访问 HTML,所以这是我唯一可以使用的类。
<div class="price-content">
<span class="old-price">
**<span class="new-price>**
<span class="percentage">
</div>
我在整个页面上都重复了这一点,默认情况下隐藏“旧价格”。但有时它有“显示: block ”。如何仅在显示“旧价”时为“新价”赋予特定颜色?
最佳答案
使用 jQuery,查找所有 .old-price
元素。如果他们有 display:block,则修改他们的同级 .new-price
元素。这是一个例子:
$(document).ready(function() {
$.each($('.price-content > .old-price'), function(i, el) {
$oldPrice = $(el);
if ($oldPrice.css('display') === 'block') {
$oldPrice.next('.new-price').css('color', 'purple');
// Or maybe do 'addClass' for semantic's sake
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price-content">
<span class="old-price" style="display: none">$5.98</span>
<span class="new-price">$5.15</span>
<span class="percentage">14%</span>
</div>
<hr />
<div class="price-content">
<span class="old-price" style="display: block">$5.98</span>
<span class="new-price">$5.15</span>
<span class="percentage">14%</span>
</div>
关于html - 选择下一个兄弟,仅当显示此跨度时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42842714/