iT邦幫忙

0

[css] 挑出最後一個與第一個元素

css
Zaku 2019-03-29 15:01:128469 瀏覽

想請問一下假定有n個元素,有辦法挑出第一個跟最後一個元素設定不同樣式嗎?

假設結構如下:

<div class="a">
    <div class="b"></div>
    <div class="b"></div>
    <div class="b"></div>
    .
    .
    .
    <div class="b"></div>
</div>

a底下有n個b,可否挑出第一個b和最後一個b

moonfish iT邦新手 4 級 ‧ 2019-03-29 15:05:24 檢舉
jquery .first() 跟 .last() 可以做到
froce iT邦大師 1 級 ‧ 2019-03-29 15:38:10 檢舉
https://www.w3schools.com/cssref/css_selectors.asp
Zaku iT邦新手 3 級 ‧ 2019-04-01 17:33:06 檢舉
感謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
㊣浩瀚星空㊣
iT邦大神 1 級 ‧ 2019-03-29 15:05:06
最佳解答
.a .b{color:#000}
.a .b:first-child{color:#fff} #第一個
.a .b:last-child{color:#ccc}  #最後一個
Zaku iT邦新手 3 級 ‧ 2019-04-01 17:25:43 檢舉

感謝大大https://www.w3schools.com/cssref/sel_last-of-type.asp
這個也可以吧

是的。這是針對子元素的控制。不過我很少用這個就是了。
因為指定class的方式會比較適合我的控制。

1
舜~
iT邦高手 1 級 ‧ 2019-03-29 17:26:07

樓上應該就能回答樓主,小弟來湊一腳XD

位置|jquery | css(copy樓上浩瀚星空的)
--|--
第一個|$('div.b:first') ; $('div.b').first() ; $('div.b:nth-child(1)');$('div.b:eq(0)');| .a .b:first-child{color:#fff}
最後一個|$('div.b:last') ; $('div.b').last();$('div.b:eq(-1)');| .a .b:last-child{color:#fff}

用jQuery抓出第一個獲最後一個元素,就可以自己DIY,動態處理樣式了~~

jquery、css的選擇器基本上是一樣的
:eq(N), :nth(N):找出選擇結果集 index 為 N 的 elements
:gt(N):找出結果集中索引大於 N 的 elements
:lt(N):找出結果集中索引小於 N 的 elements
:first:找出結果集中的第一個 element (相當於 eq(0) 或者 nth(0))
:last:選擇結果集中的最後一個 element
更多可參考:https://ithelp.ithome.com.tw/articles/10095237

備註:
first-child、last-child小弟在jquery上面測試不符預期,您要自行測試一下

看更多先前的回應...收起先前的回應...
米歐 iT邦新手 3 級 ‧ 2019-03-29 17:52:17 檢舉

first-child、last-child 不是JS 是CSS
我猜你放在script 不是style

froce iT邦大師 1 級 ‧ 2019-03-29 19:39:50 檢舉

jQ的選擇子比較多。
像是 :animated :checkbox 之類的是jQ的自創選擇子。
用的時候要小心。

舜~ iT邦高手 1 級 ‧ 2019-03-30 00:17:14 檢舉

米歐: first-child、last-child 在jQuery中也有喔~

米歐 iT邦新手 3 級 ‧ 2019-04-01 14:49:36 檢舉

哈哈 誤會了 /images/emoticon/emoticon20.gif

Zaku iT邦新手 3 級 ‧ 2019-04-01 17:25:55 檢舉

感謝

我要發表回答

立即登入回答