Javascript jquery-根据文档宽度折叠面板

Javascript jquery-根据文档宽度折叠面板,javascript,jquery,Javascript,Jquery,如果文档宽度小于514,我想缩小面板。我的脚本不起作用: jQuery(document).ready(function($){ if ($(document).width() < 514) { if (!$('.panel-heading').hasClass('panel-collapsed')) { // collapse the panel $(this).parents('.pan

如果文档宽度小于514,我想缩小面板。我的脚本不起作用:

    jQuery(document).ready(function($){

    if ($(document).width() < 514) {

            if (!$('.panel-heading').hasClass('panel-collapsed')) {
            // collapse the panel
                $(this).parents('.panel').find('.panel-body').slideUp();
                $(this).addClass('panel-collapsed');
                $(this).find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
            }

    };
});
以及HTML:

<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Panel 1</h3>
     <span class="pull-right clickable"><i class="glyphicon glyphicon-chevron-up"></i></span>
  </div>

 <div class="panel-body"> Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.
</div>

 </div>
</div>

小组1
肘关节或肘关节前前庭。
谢谢,
贾斯汀

您应该将
引用替换为用于
单击事件的选择器

jQuery(document).ready(function($){

if ($(document).width() < 514) {
        var tar = $('.panel-heading span.clickable');
        if (!$('.panel-heading').hasClass('panel-collapsed')) {
        // collapse the panel
            tar.parents('.panel').find('.panel-body').slideUp();
            tar.addClass('panel-collapsed');
            tar.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        }

};
jQuery(文档).ready(函数($){
if($(文档).width()<514){
var tar=$('.panel heading span.clickable');
if(!$('.panel heading').hasClass('panel-collapsed')){
//折叠面板
tar.parents('.panel').find('.panel body').slideUp();
tar.addClass(“面板折叠”);
tar.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
}
};

}))

您正在运行调整大小的
$(document).width()
检查,还是这是第一次运行行为?您的第一个代码段(
if($(document).width()<514){…}
)在哪里?什么时候运行它?在工作和非工作代码段中,您都在使用
$(this)
进行修改。请注意,它与您计算
span的元素不同。一个元素中的clickable
,另一个元素中的clickable
。面板标题。我正在运行位于顶部的if($(document).width()<514),后面是:jQuery(document).ready(function($){我只想在初始加载时检查条件,不想调整大小。您可以上载html代码和/或JSFIDLE吗
jQuery(document).ready(function($){

if ($(document).width() < 514) {
        var tar = $('.panel-heading span.clickable');
        if (!$('.panel-heading').hasClass('panel-collapsed')) {
        // collapse the panel
            tar.parents('.panel').find('.panel-body').slideUp();
            tar.addClass('panel-collapsed');
            tar.find('i').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
        }

};