首页 > 解决方案 > CSS 过渡有不一致的延迟

问题描述

我正在构建一个带有滑动动画的简单下拉菜单。菜单向上滑动后,它会应用 CSS 使下拉菜单不可见,但仍可通过屏幕阅读器访问。

问题:当我按下按钮展开下拉菜单时,它立即展开。但是,当我按下按钮折叠下拉菜单时,它有很大的延迟(这需要修复)。

片段

//accessible hiding sliding test

var sliderButton = document.getElementById('slider-button');
var slider = document.getElementsByClassName('slider')[0];

// toggle closed class to start max-height transition animation
sliderButton.addEventListener("click", function(){

    if(slider.classList.contains('closed')){
        slider.classList.remove('closed');
        slider.classList.remove('sr-only');
    }else{
        slider.classList.add('closed');
    }
});

// after finishing transition, if its closed, add 'sr-only' for  accessible hiding!
slider.addEventListener('transitionend', function(event){

  if(event.propertyName == 'max-height'){
    if(slider.classList.contains('closed')){
      slider.classList.add('sr-only');
    }
  }
});
.slider {
    position: absolute;
    overflow-y: hidden;
    white-space: nowrap;
    max-height: 500px; /* approximate max height */
    width: 250px;
    left: 10px;

      transition-property: max-height;
    transition-duration: 1s;
    transition-delay: 0s;
    background-color: lawngreen;
}

.slider.closed {
    max-height: 1px;
}

.sr-only{ /* screen reader accessible hiding! */
    border: 0;
    clip: rect(0 0 0 0);
    clip-path: polygon(0px 0px, 0px 0px, 0px 0px);
    -webkit-clip-path: polygon(0px 0px, 0px 0px, 0px 0px);
    max-height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
    white-space: nowrap;
  }
<a id="slider-button">click here to toggle the content!</a>

<ul class="slider">
  <li>Women</li>
  <li>Men</li>
  <li>Camping</li>
  <li>Blog</li>
  <li>Theme Info</li>
</ul>

从上面的下拉菜单中可以看出,下拉菜单有无常的延迟,有什么办法可以解决这个问题吗?

标签: javascripthtmlcssdrop-down-menuaccessibility

解决方案


尝试用高度替换最大高度。在我看来,他无法计算这些值。


推荐阅读