Js点击事件第一次获取不到值

247 阅读1分钟

问题:二级菜单click事件无法获取第一次点击的值,代码二次点击后才生效

     let ul = document.querySelector('ul');
        ul.addEventListener('click', function (e) {
            let box = e.target.parentNode.children[1];
            if (box.style.display == 'none') {
                box.style.display = 'block';
            } else {
                box.style.display = 'none';
            }
        })
   

原因:style对象只能获取到内联/行内样式。因此click第一次取得的是行内样式,css样式的值无法获取,即第一次取值为display=''

解决:

改为:

 let ul = document.querySelector('ul');
        ul.addEventListener('click', function (e) {
            let box = e.target.parentNode.children[1];
          ! let dis = window.getComputedStyle(box, null).display;
            if (dis == 'none') {
                box.style.display = 'block';
            } else {
                box.style.display = 'none';
            }
        })

Window.getComputedStyle()

  • getComputedStyle获取计算完成后的CSS属性值,只读

     语法: let style = window.getComputedStyle("元素", "伪类");
    

    例如:

        let ul = document.querySelector('ul');
        let left = window.getComputedStyle(ul, '::after').left;
    
  • getComputedStyle与style的区别

    • 应用不同:
      • getComputedStyle:只读
      • style:可读可写
    • 获取对象范围不同:
      • getComputedStyle:最终应用在元素上的所有CSS属性对象
      • style:只能获取元素style属性中的CSS样式
       <p></p>
       let p = document.querySelector('p');
       let ps = window.getComputedStyle(p, null).display;
       console.log(p.style.display); // ''
       console.log(ps); // block  默认值
      
  • getPropertyValue:获取CSS样式申明对象上的属性值 (只读

     let ps = window.getComputedStyle(p, null).getPropertyValue('width') //100px