js实现省市区三级联动非select下拉框版
在网上搜三级联动发现都是用option写的,突发奇想用其他方式写了一个,自我感觉效果还不错,大家感兴趣的可以看看,不说废话,大家看效果
代码如下,小白写的有点乱,大家想看的就看看
1.html代码
<div class="box"> <section class="province">省</section> <section class="city">市</section> <section class="area">区</section> <div class="si"> </div> </div>
2.css代码
<style> .box{ width: 800px; height: 50px; margin: 20px auto; background-color: rgb(48, 49, 48); border-radius: 10px; display: flex; justify-content: center; align-items: center; } .box section{ display: inline-block; background-color: rgb(168, 165, 165); flex-grow: 1; height: 30px; margin-right: 10px; margin-left: 10px; border-radius: 5px; line-height: 30px; padding-left: 10px; } .box section:hover{ cursor: pointer; } .si{ display: none; } .box .all{ display: block; width: 740px; background-color: rgb(211, 203, 203); padding: 20px; position: absolute; border-radius: 10px; top: 57px; } .box .all:hover{ cursor: pointer; } .box .all span{ display: inline-block; width: 130px; height: 30px; font-size: 13px; padding-left: 10px; line-height: 30px; border-radius: 5px; margin-left: 10px; border: 1px solid #000; background-color: white; box-sizing: border-box; margin-top: 10px; } </style>
3.js代码
<script> // 获取内容 var data = city_code// 这个是我的数据 // 获取省市区 var province = document.querySelector(".province") var city = document.querySelector(".city") var area = document.querySelector(".area") // 获取隐藏div var si = document.querySelector(".si") province.addEventListener("mouseover",function(){ si.classList.add("all") // 选择省 var html = "" var all = document.querySelector(".all") for(var i = 0;i<data.length;i++){ const provinceName = data[i].name const provinceID = data[i].code html += `<span id="${provinceID}">${provinceName}</span>` } all.innerHTML=html var spanAll = document.querySelectorAll("span") for(var j =0;j<spanAll.length;j++){ spanAll[j].addEventListener("click",function(){ province.innerHTML=this.innerText province.id=this.id html = "" // 选择市 for(var k = 0;k<data.length;k++){ if (data[k].code===province.id) { var citys = data[k].city for(var i = 0;i<citys.length;i++){ html +=`<span id="${citys[i].code}">${citys[i].name}</span>` } all.innerHTML=html var spanAll = document.querySelectorAll("span") for(var j =0;j<spanAll.length;j++){ spanAll[j].addEventListener("click",function(){ city.innerHTML=this.innerText city.id=this.id html = "" //选择区 for(var k = 0;k<citys.length;k++){高防iphttp://www.558idc.com/gfip.html if (citys[k].code===city.id) { var areas = citys[k].area for(var i = 0;i<areas.length;i++){ html +=`<span id="${areas[i].code}">${areas[i].name}</span>` } all.innerHTML=html var spanAll = document.querySelectorAll("span") for(var j =0;j<spanAll.length;j++){ spanAll[j].addEventListener("click",function(){ area.innerHTML=this.innerText area.id=this.id si.classList.remove("all") }) } break } } }) } break } } }) } }) </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持hwidc。