手风琴可以在移动设备上关闭所有部分,但在平板电脑和台式机上总是打开一个手风琴部分

Accordion that can have all sections closed on mobile, but always has one accordion section open on tablets and desktop

本文关键字:手风琴部 台式机 平板电脑 一个 移动 手风琴      更新时间:2023-09-26

我有一个手风琴,每次只打开一个部分。在台式机/平板电脑的屏幕尺寸上,总是需要有一个部分是打开的,这样就不会有空白区域。但是在移动设备上,这个相同的手风琴将需要关闭所有部分的能力(即,如果你点击一个已经打开的部分,它将关闭,而其他部分不会打开)。

这是我到目前为止的一个概要。似乎嵌套的if else语句没有被触发,并且只使用来自未嵌套的if else语句的else。https://jsfiddle.net/bluebomber/x40jq16L/1/

这是我目前正在使用的jQuery:

$('li').click(function(width) {
   var thisClicked = $(this);
   if (width <= 767) {
      if (thisClicked.hasClass('selected')) {
         $('li').removeClass('selected');
      } else {
         $('li').removeClass('selected');
         thisClicked.addClass('selected');
      }
   } else {
      $('li').removeClass('selected');
      thisClicked.addClass('selected');
   }
});

您使用width,但是with是一个关于事件单击的信息对象。

如果你使用console.log(width);,你可以看到对象。试试这个:

$('.tabs.standard > ul > li').click(function(event) {
   console.log(event); // event(before called width) is a object, no integer or numeric value...
   var thisClicked = $(this),
   width = $(this).outerWidth(); // This calculate width
   if (width <= 767) {
      if (thisClicked.hasClass('selected')) {
         $('.tabs.standard > ul > li').removeClass('selected');
      } else {
         $('.tabs.standard > ul > li').removeClass('selected');
         thisClicked.addClass('selected');
      }
   } else {
      $('.tabs.standard > ul > li').removeClass('selected');
      thisClicked.addClass('selected');
   }
});

了解outerWidth在这里:http://api.jquery.com/outerwidth/