CSS+JQuery實(shí)現(xiàn)給一組元素動(dòng)態(tài)的添加序號(hào)

最近做項(xiàng)目,遇到需要實(shí)現(xiàn)對(duì)一組元素進(jìn)行動(dòng)態(tài)的排序并生成序號(hào)的功能,以下是具體實(shí)現(xiàn):

1. 實(shí)現(xiàn)思路

給這組元素綁定點(diǎn)擊事件,當(dāng)點(diǎn)擊某個(gè)元素時(shí),判斷是否已經(jīng)排序,若已經(jīng)排序則需要給這個(gè)已排序的元素重新進(jìn)行排序,并且當(dāng)前單擊的元素要清除其序號(hào),若是沒(méi)有進(jìn)行過(guò)排序,則獲取已經(jīng)排序了的元素,在得到的數(shù)組的長(zhǎng)度上加1即是當(dāng)前元素的序號(hào);

2. 示例代碼

html

<ul>

<li><span class="sort-item"></span>item1</li>

<li><span class="sort-item"></span>item2</li>

<li><span class="sort-item"></span>item3</li>

</ul>

css

html,body {

width: 100%;

height:? 100%;

font-family: 'Microsoft YaHei';

}

ul, ul li {

list-style: none;

}

.order-list {

width:? 60%;

margin: 30px auto;

}

.order-list? li {

width:? 100%;

height:? 34px;

line-height: 34px;

padding: 0 15px;

cursor:? pointer;

background: #f2f2f2;

margin:? 10px 0;

border-radius: 5px;

}

.sort-item {

width:? 15px;

height:? 15px;

border:? 1px solid #ccc;

float:? left;

background:? #ccc;

font-size:? 12px;

margin-right:? 10px;

margin-top: 10px;

text-align: center;

border-radius: 4px;

color:? #666;

}

.sort-item-select {

width: 15px !important;

height: 15px !important;

line-height: 15px;

border-radius: 100%;

border-color: #ff6600;

color: #ff6600;

background: none;

border-radius: 100%;

}

js

//給需要排序的選項(xiàng)綁定點(diǎn)擊事件

$('.order-list li').bind('click',function() {

var that = this;

//檢測(cè)是否已經(jīng)排序?

if ($(that).attr('sorted') != 1) {//否

//獲取已經(jīng)排序了的元素,并且當(dāng)前元素的序號(hào)應(yīng)該在已排序元素長(zhǎng)度的基礎(chǔ)上加1

var checkLn = $(that).parent().find('li[sorted="1"]').length + 1;

//給當(dāng)前元素設(shè)置排序的序號(hào)值以及顏色

$(that).find('span.sort-item').html(checkLn).addClass('sort-item-select');

//設(shè)置當(dāng)前元素已經(jīng)排序了

$(that).attr('sorted','1');

} else {//是,再次點(diǎn)擊時(shí)需要清除需要,并重新排序

//獲取當(dāng)前元素的序號(hào)元素的內(nèi)容

var checkLn = $(that).find('span.sort-item').html();

//遍歷已排序元素,并判斷當(dāng)前元素和已排序的元素的大小

$(that).parent().find('li[sorted="1"]').each(function(index,ele) {

var nSpan = $(this).find('span.sort-item').html();

//大于零,則減一,重新給已排序的元素排序

if (nSpan - checkLn > 0) {

$(this).find('span.sort-item').html(nSpan - 1);

}

});

//移除序號(hào)以及樣式

$(that).find('span.sort-item').html('').removeClass('sort-item-select');

$(that).attr("check", "");

}

});

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容