如何js实现标签切换,改变内容classname

2025-05-18 22:45:23
推荐回答(1个)
回答1:

给你个Demo,拿去参考。

body



    

        房产
        家具
        
  • 二手房



    

275万购昌平邻铁三居 总价20万买一居 

        200万内购五环三居 140万安家东三环

        北京首现零首付楼盘 53万购东5环50平

        京楼盘直降5000 中信府 公园楼王现房


     40平出租屋大改造 美少女的混搭小窝

        经典清新简欧爱家 90平老房焕发新生

        新中式的酷色温情 66平撞色活泼家居

        瓷砖就像选好老婆 卫生间烟道的设计


     通州豪华3居260万 二环稀缺2居250w甩

        西3环通透2居290万 130万2居限量抢购

        黄城根小学学区仅260万 121平70万抛!

        独家别墅280万 苏州桥2居优惠价248万



css

ul{
    padding: 0;
    margin: 0;
}
li{
    list-style: none;
    display: block;
    float: left;
    cursor:pointer;
    border: 1px #aaaaaa solid;
    border-bottom: none;
    background: white;
    margin-right: 10px;
    padding-left: 10px;
    padding-right: 10px;
}
.active{
    border-top:2px firebrick solid ;
    border-bottom:2px white solid ;
    position: relative;
}
ul:first-child{
    padding-left: 10px;
}
.clearfloat{
    clear: both;
    width: 300px;
    border: 1px #CCCCCC solid;
    border-top: 2px firebrick solid;
    position: relative;
    top: -2px;
    z-index: -1;
}
.hidden{
    display: none;
}

js实现方法

window.onload = function () {
    var oLis = document.getElementsByTagName('li');
    var oPs = document.getElementsByTagName('p');
    for (var i = 0; i < oLis.length; i++) {
        oLis[i].index = i;
        oLis[i].onclick = function () {
            for (var n = 0; n < oLis.length; n++) {
                oLis[n].className = '';
                oPs[n].className = 'hidden';
            }
            this.className = 'active';
            oPs[this.index].className= ''
        }
    }
}

jq实现方法

window.onload = function () {
    $('li').on('click',function () {
        $('li').removeClass('active');
        $(this).addClass('active');
        $('p').addClass('hidden');
        var i = $('li').index(this);
        document.getElementsByTagName('p')[i].className=''
    })
}

相关问答