gpt4 book ai didi

javascript - 在 CSS 排序后定位第一个元素

转载 作者:太空狗 更新时间:2023-10-29 12:31:35 24 4
gpt4 key购买 nike

请参阅此代码笔:http://codepen.io/muji/pen/XpEYzO

我需要将第一个元素作为目标之后它已按 css“order”属性排序并为其提供另一个 CSS 属性。

是否有一些 jQuery 或其他东西可以用来在排序后找到第一个元素,然后是 addClass 或其他东西?非常感谢您的帮助

.wrap {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.featured {
order: 1;
}
.normal {
order: 2;
}
.wrap div {
flex-basis: 50%;
background: #ddd;
border: 2px solid #000;
}

/*this is the part I need help with, as it should only apply to the first element AFTER applying the "order" attribute*/
.wrap div:first-of-type {
flex-basis: 100%;
background: #f00;
}
<h3>wp_query 1 output:</h3>
<div class="wrap">
<div class="normal">Normal</div>
<div class="normal">Normal</div>
<div class="featured">A featured item</div>
<div class="normal">Normal</div>
<div class="featured">A featured item</div>
<div class="normal">Normal</div>
</div>

<h3>wp_query 2 output:</h3>
<div class="wrap">
<div class="normal">Normal</div>
<div class="normal">Normal</div>
<div class="normal">Normal</div>
<div class="normal">Normal</div>
</div>

最佳答案

我不知道有任何 CSS selector对于“顺序优先”之类的(很方便,因为 order 被更广泛地采用),所以它可能需要是一个基于脚本的解决方案(悲伤地)。

您曾指出涉及重新排序 元素的解决方案可能适合您。如果是这样,那就太容易了。 :-) 查看评论:

// A worker function to tell us the priority of an element (low number = high priority)
function getPriority($el) {
return $el.hasClass("featured") ? 0 : $el.hasClass("normal") ? 1 : 2;
}
// For each .wrap container...
$(".wrap").each(function() {
var $this = $(this);

// Get an array of its child elements
var a = $this.children().get();

// Sort it, putting featured first, then normal, then any others
a.sort(function(a, b) {
return getPriority($(a)) - getPriority($(b));
});

// Append them to the parent, which moves them
$this.append(a);
});
.wrap {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.wrap div {
flex-basis: 50%;
background: #ddd;
border: 2px solid #000;
}

/* Just make the first div the highlighted one */
.wrap div:first-of-type {
flex-basis: 100%;
background: #f00;
}
<h3>wp_query 1 output:</h3>
<div class="wrap">
<div class="normal">Normal</div>
<div class="normal">Normal</div>
<div class="featured">A featured item</div>
<div class="normal">Normal</div>
<div class="featured">A featured item</div>
<div class="normal">Normal</div>
</div>

<h3>wp_query 2 output:</h3>
<div class="wrap">
<div class="normal">Normal</div>
<div class="normal">Normal</div>
<div class="normal">Normal</div>
<div class="normal">Normal</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 在 CSS 排序后定位第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41999703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com