文章出處
文章列表
【功能說明】
最簡單的可取消多選效果(以從水果籃中挑選水果為例)
【html代碼說明】
<div class="box" id="box"> <input class="out" placeholder = "請挑選我要的水果" disabled> <button class="btn">合上我的水果籃子</button><br> <ul class="list"> <li class="in red">蘋果</li> <li class="in purple">葡萄</li> <li class="in yellow">香蕉</li> <li class="in green">青梅</li> <li class="in orange">桔子</li> </ul> </div>
【css重點代碼說明】
//設置展示框中乳白色文字效果 .out{ width: 300px; height:30px; line-height: 50px; padding: 10px; text-align: center; border: 1px solid #ccc; border-radius: 5px; font-size: 20px; color: #f1ebe5; text-shadow: 0 8px 9px #c4b59d, 0px -2px 1px #fff; font-weight: bold; background: linear-gradient(to bottom, #ece4d9 0%,#e9dfd1 100%); vertical-align: middle; } //水果籃顯示效果 .list,.list_hid{ height: 50px; line-height: 50px; margin-top: 20px; overflow: hidden; text-align: center; background-color: #ccc; border-radius: 10px; transition: 500ms height; } //水果籃隱藏效果 .list_hid{ height: 0; }
【js代碼說明】
//獲取整個盒子 var oBox = document.getElementById('box'); //獲取按鈕 var oBtn = oBox.getElementsByTagName('button')[0]; //獲取展示框 var oOut = oBox.getElementsByTagName('input')[0]; //獲取水果籃子 var oList = oBox.getElementsByTagName('ul')[0]; //獲取水果籃子里面的所有水果 var aIn = oList.getElementsByTagName('li'); //給按鈕綁定事件 oBtn.onclick = function(){ //若list的className為list,說明此時水果籃子處于打開狀態 if(oList.className == 'list'){ //更改其className為list_hid,關閉水果籃子 oList.className = 'list_hid'; //設置文字顯示為打開我的水果籃子 this.innerHTML = '打開我的水果籃子'; //此時水果籃子處于關閉狀態 }else{ //更改其className為list,打開水果籃子 oList.className = 'list'; //設置文字顯示為合上我的水果籃子 this.innerHTML = '合上我的水果籃子'; } } for(var i = 0; i < aIn.length; i++){ //給每個水果添加標記,默認為false,表示未被選中 aIn[i].mark = false; //給每個水果添加事件 aIn[i].onclick = function(){ //當水果選中時,取消選中;當水果未選中時,將其選中 this.mark = !this.mark; //若該水果選中,則文字顏色變為亮灰色 if(this.mark){ this.style.color = '#ccc'; //若未選中,則文字顏色為黑色 }else{ this.style.color = 'black'; } //運行展示框函數 fnOut(); } } //設置展示框函數 function fnOut(){ //設置臨時字符串,來存儲展示框要顯示的值 var str = ''; for(var i = 0; i < aIn.length; i++){ //當該水果被選中時 if(aIn[i].mark){ //將其innerHTML添加到臨時字符串中 str += ',' + aIn[i].innerHTML; } } //再將最開始第一個水果前的逗號去掉 oOut.value = str.slice(1); };
【效果展示】
文章列表
全站熱搜