slideToggle()函数在缩小后不起作用

slideToggle() Function does not work after scaling down

本文关键字:缩小 不起作用 函数 slideToggle      更新时间:2023-09-26

我的代码中有一个令人困惑的错误,不知道如何修复它。我开始使用main函数,根据当前窗口大小调用脚本。

对于移动设备,我有一个slideToggle()函数,它在移动设备上查看时确实有效。但当打开600px以上时,按比例缩小功能被触发,但slideToggle();不再工作。

设置为display: block;,立即再次设置为display: none;。我的slideToggle();是这样嵌入的:

$('.box-header').on('click', function() {
  $(this).parent().toggleClass('folded').toggleClass('unfolded');
  $(this).next('div').stop().slideToggle();
  console.log('clicked');
});
<<p> JSFIDDLE演示/strong>

在观看演示时,重要的是在窗口大小大于600px时加载页面,然后缩小以重现问题。如果它工作,请再试一次,因为它有时确实工作。

我错过了什么?是否有更好的方法来杀死和调用脚本取决于观众视口后调整大小事件?

把if放到click事件中:

  $('.box-header').on('click', function() {
    if ($(window).width() < 600) {
      $(this).parent().toggleClass('folded unfolded');
      $(this).next('div').stop().slideToggle();
    } else {
      //for other code here for medium+large screens
    }
  });
https://jsfiddle.net/5puqn9ts/1/

甚至使用一个类来切换移动和大屏幕,绑定一个点击事件到每个

$(document).ready(function() {
    $('body').on('click', '.mobile', function() {
      $(this).parent().toggleClass('folded').toggleClass('unfolded');
      $(this).next('div').stop().slideToggle();
      console.log('clicked');
    });

  // init scripts for smartphone or desktops
  var initScripts = function() {
    if ($(window).width() < 600) {
      $('.box-header').addClass('mobile');
    }
    if ($(window).width() >= 600) {
      $('.box-header').removeClass('mobile');
      /add class for medium screen then bind event to ti
    }
  }
  initScripts();
  var id;
  $(window).resize(function() {
    initScripts()
  });
});
https://jsfiddle.net/75186j96/5/

你的函数在每次调用中设置一个事件。试试这个正确的选项:

var smartphoneFunctions = $('.box-header').on('click', function() {
  $(this).parent().toggleClass('folded').toggleClass('unfolded');
  $(this).next('div').stop().slideToggle();
  console.log('clicked');
});
https://jsfiddle.net/75186j96/8/

要回答您的问题,您需要将slideToggle()目标调整为.box-content而不是抽象的div,因为这将在.box-header上应用开关。你的类切换也可以被捆绑。

结果代码如下:

$('.box-header').on('click', function() {
  $(this).parent().toggleClass('folded unfolded');
  $(this).next('.box-content').stop().slideToggle();
  console.log('clicked');
});

话虽如此,有更好的方法来做到这一点。您可以将类绑定到.box-content的外观,如下所示:

.box-content {
    transition: height 300ms;
    overflow: hidden;
}
.box.folded .box-content {
    max-height: 0;
}
.box.unfolded .box-content {
    max-height: 300px;
}