Accordian Dropdown不适用于手机/平板电脑

Accordian Dropdown not working on mobile/tablet

本文关键字:平板电脑 手机 适用于 Dropdown 不适用 Accordian      更新时间:2023-09-26

我的网站上有一个相应的常见问题下拉菜单。在手机上,当敲击小节时,手风琴会下降,然后迅速消失。我希望答案部分下降(可能有一个平稳的过渡)并停留,直到再次单击"问题"栏或另一个问题栏。我使用以下代码:

JS-

    <script> 
$(document).ready(function(){
  $(document).on('touchstart mousedown', '.acc-btn', function(){
    // If you only want one visible at a time:
    $('.acc-container').find('.selected').not(this).removeClass('selected');
    // ^^ 'closes' everything by removing the class selected.
    // Except the one we just clicked, otherwise it wouldn't toggle—
    // the class would get removed and added back two lines down.

    $(this).toggleClass('selected');
  });
});</script>

HTML

<div class="acc-container">
<div class="acc-btn"><h1>What is Company?</h1></div>
<div class="acc-content">
<div class="acc-content-inner">
<p> Answer blah blah</p>
</div>
</div>

CSS

.acc-container {
  width:90%;
  margin:30px auto 0 auto;
  overflow:hidden;
}
.acc-btn { 
 font-family: "Oswald", sans-serif;
font-weight:lighter;
text-transform: uppercase;
padding: 5px 5px 5px 5px;
margin-bottom:3px;
height: 100%;
cursor: pointer;
}

.acc-content {
  max-height:0px;
  width:100%;
  margin:0 auto;
  overflow:hidden;
  background:#C9C8C8;
  color:#000000;
  /*-webkit-transition: all 0.35s ease-in-out 0s;
  -moz-transition: all 0.35s ease-in-out 0s;
  transition: all 0.35s ease-in-out 0s;*/
}
.selected + .acc-content {
    max-height: 700px;
}
.acc-content-inner {
  padding:30px;
}
.open {
  height: auto;
}

快速简单的解决方案是更换

$(document).on('touchstart mousedown',

$(document).on('click',

原因

您编写的代码将打开/关闭逻辑连接到touchstart和mousedown事件。问题是,在大多数当前的移动设备上,物理触摸用于触发触摸事件鼠标事件。这是为了提高与非触摸友好网站的兼容性。

这会给你带来麻烦,因为一旦其中一个运行,另一个就会撤销你刚刚做的事情。

不过,您可以使用这种行为,因为触摸事件也被注册为点击,这意味着处理点击事件将通过一次调用覆盖鼠标和基于触摸的设备。否则,在运行鼠标事件之前,您必须创建逻辑来检查触摸事件是否已处理,反之亦然。

这确实会稍微改变你的行为,因为点击并不是完全复制鼠标向下(点击需要在启动之前按下和释放按钮),而是更标准的行为,我认为这就是你想要的。

事件可能被触发两次,所以您可以做的是防止事件在DOM树中冒泡:

$(document).on('touchstart mousedown', '.acc-btn', function(e){
    e.stopImmediatePropagation();
    /* ... REST OF THE CODE ... */
});