最简单的可取消多选效果(以从水果篮中挑选水果为例)【jsDEMO】

【功能说明】
  最简单的可取消多选效果(以从水果篮中挑选水果为例)


【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);
};

 

【效果展示】

 

【源码查看】

posted @ 2015-09-15 00:46  小火柴的蓝色理想  阅读(1477)  评论(0编辑  收藏  举报