原生JS实现‘点击元素切换背景及字体等’
通过原生JS,实现点击某元素,使得背景颜色和文本样式及颜色的改变。
1、HTML部分
<body> <div class="top"> <span onclick="colChange()" id='span1'> <section class="s11"> <p class="sp111">TOP 6</p> <p class="sp112">品牌人气榜</p> </section> <section class="s12"> <div id='t1' class="sd12"></div> </section> </span> <span onclick="colChange()" id='span2'> <section class="s21"> <p class="sp211">TOP10</p> <p class="sp212">高校贡献榜</p> </section> <section class="s22"> <div id='t2' class="sd22"></div> </section> </span> </div> </body>
2、CSS部分
<style> .top{ display: flex; position: absolute; left: 50%; transform: translateX(-50%); } span{ width: 12.28rem; height: 3.57rem; border-radius: 75px; margin-top: 1.03rem; } span:first-child{ margin-left: 0.86rem; background: #FEDC53; } span:last-child{ margin-left: 0.48rem; background: #B80027; } /* 第一个top */ .s11, .s21{ overflow: scroll; white-space: nowrap; width: 8.72rem; height: 3.57rem; float: left; } .sp111, .sp211{ height: 1.04rem; font-family: 'DIN-Bold'; font-weight: bold; color: #C41B28; font-size: 1.42rem; margin-left: 3.54rem; } .s12, .s22{ width: 3.56rem; height: 3.57rem; float: left; position: relative; } .sd12, .sd22{ width: 0.95rem; height: 0.95rem; background-image: url('../images/section/top1.png'); background-size: 100% 100%; margin-top: 1.30rem; border-radius: 20px; position: absolute; } .sd22{ background-image: url('../images/section/top2.png'); background-size: 100% 100%; } /* 第二个TOP颜色整改 */ .sp211, .sp212{ color:#FF9BAA; } .sp22{ position: relative; margin-top: 0.3rem; border: 0.47rem solid; border-color: #B80027 transparent transparent; } </style>
3、Javascript部分
主要是利用className进行的样式切换
<script> //颜色切换 let colChange = ()=>{ let d1 = document.getElementById('t1'); console.log(d1.className); if(d1.className === 'sd12'){ d1.className = 'sd22'; let s1 = document.getElementById('span1'); s1.style.background= '#B80027'; s1.getElementsByTagName('section')[0].children[0].className = 'sp211'; s1.getElementsByTagName('section')[0].children[1].className = 'sp212'; }else if(d1.className === 'sd22'){ d1.className = 'sd12'; let s1 = document.getElementById('span1'); s1.style.background= '#FEDC53'; s1.getElementsByTagName('section')[0].children[0].className = 'sp111'; s1.getElementsByTagName('section')[0].children[1].className = 'sp112'; } let d2 = document.getElementById('t2'); if(d2.className === 'sd22'){ d2.className = 'sd12'; let s1 = document.getElementById('span2'); s1.style.background= '#FEDC53'; s1.getElementsByTagName('section')[0].children[0].className = 'sp111'; s1.getElementsByTagName('section')[0].children[1].className = 'sp112'; }else if(d2.className === 'sd12'){ d2.className = 'sd22'; let s1 = document.getElementById('span2'); s1.style.background= '#B80027'; s1.getElementsByTagName('section')[0].children[0].className = 'sp211'; s1.getElementsByTagName('section')[0].children[1].className = 'sp212'; } } </script>