js原生 toggle函数编写

 

 工作中遇到了需要动态切换slide下拉框展示与隐藏,同时需要切换元素上附加的样式,以下脚本为实现此功能的实践。

//元素点击时切换隐藏与展示逻辑
var slidsDownShow = document.querySelectorAll('div.deliveryArea__link > span');
    if(slidsDownShow){
        slidsDownShow.forEach(function(item){
            item.addEventListener("click",function(e){
            var tar = e.target || e.srcElement;
            if(tar.parentElement.nextElementSibling.style.display != 'block'){
                tar.parentElement.nextElementSibling.style.display = 'block';
            }else{
                tar.parentElement.nextElementSibling.style.display = 'none';
            }
            console.log('click info1 ..')});
        })
        
    }
    //定义切换样式的函数
    function toggleClass(ele,cln) {
      if ((' ' + document.querySelector(ele).className + ' ').indexOf(' ' + cln + ' ') > -1) {
        document.querySelector(ele).classList.remove(cln)
      } else {
        document.querySelector(ele).classList.add(cln)
      }
    }
 
    var subEles = document.querySelectorAll('.deviceInfoArea__infoTitle');
    subEles.forEach(function (item) {
      item.addEventListener('click', function () {
        //调用上面的方法
        toggleClass('.deviceInfoArea__infoTitle','open')
        if(this.nextElementSibling.style.display == 'block'){
            this.nextElementSibling.style.display = 'none';
        }else{
            this.nextElementSibling.style.display = 'block';
        }
      })
    })

 

posted @ 2022-08-09 16:28  辉兔子  阅读(172)  评论(0编辑  收藏  举报