【问题标题】:Bootstrap Carousel Next/Prev controls stop responding when page is reloadedBootstrap Carousel Next/Prev 控件在页面重新加载时停止响应
【发布时间】:2015-08-20 18:39:33
【问题描述】:

我正在使用 Bootstrap Carousel 功能。在页面初始加载时,Carousel next/prev 控件可以正常工作,但是当我重新加载页面时,这些控件不再响应点击,即使我配置的“自动”旋转幻灯片的间隔继续有效。

我已经做了很多研究,试图解决这个问题..包括在 Bootstrap Carousel 上查看大约 30 多个 stackoverflow 帖子,但没有一个为我提供任何解决方案。经过两天研究这个问题,我仍然很难过。

环境/设置:

  1. 我的浏览器是 Chrome
  2. 按以下顺序包含的库:a)jQuery 2.1.3、b)Bootstrap CSS 3.3.5、c)Bootsrap JS 3.3.5
  3. 在 Ruby on Rails 4.2 环境中运行
  4. 我的解决方案是一个纯引导解决方案(例如,除了我在网上看到的每个示例都包含 $('#carousel-generic-example).carousel() 类型语句的变体之外,没有特殊的 JS ......显然无论有没有这个语句都不会改变行为)。

我有点困惑为什么它在初始加载时可以正常工作,但在随后的重新加载时却不能。当我重新加载网页时,可能没有正确加载某些内容???也许 Rails 中的某些行为导致了这种行为?

如果有人对可能导致此行为的原因有任何理论,我很乐意听到它(即使您没有时间深入研究代码)。或者,如果您对我可以解决此问题的方法有任何具体想法。

有很多与我的解决方案相关的代码......而不是试图将它们全部复制并粘贴到这篇文章中,我认为与你“分享”它的最有效和最有效的方式是指向你我的代码所在的公共 Github 帐户,并提供项目内相关文件的映射。

首先可以在我的 Github 帐户上找到完整的代码集:gitHub site 在这个项目中,您可以在这里找到相关的代码部分:

  • app/views/application.html.erb : 外部库列表(例如,jQuery、引导文件等)
  • app/views/portfolio_items/show.html.erb :包含轮播的页面的 HTML
  • app/assets/javascripts/jet.js :查看我尝试的第 17-20、199-202 行。我不确定我是否真的需要包含 javascript,因为它似乎并没有真正影响解决方案的行为。所以我最终评论了它。
  • app/assets/stylesheets/jet.css.erb:第 2332-2354 行

注意 1: 你会看到在我的 javascript 文件中我同时使用了 $(window).load(function ()... 和 `$(document).ready(function() {' 函数。我不得不承认我对这两个函数的作用有点模糊,除了通常确保页面上的项目在 javascript 开始运行之前加载。我从一个主题中利用了我模板的一部分,我注意到他们同时使用了这两个功能在他们的主题,所以我不认为这是我的问题的原因......但我想我会参考它以防万一。

注意 2:我不确定它是否相关,但我还在与 Bootstrap Carousel 的同一页面上使用了另一个 Carousel 解决方案 (caroufredsel)。我不认为有任何冲突,因为我借用的主题做了同样的事情......但我想我会提到它。

更新:我继续尝试解决我的问题(即,Bootstrap Carousel 下一个/上一个按钮不推进图像)并且偶然发现了一些有趣的东西,这可能是解决我的问题的关键问题。具体

当我立即“关闭” $(document).ready" 语句时,如下所示:

  • '$(document).ready(function() {});'

在我的 javascript“app/assets/javascripts/jet.js”中,Bootstrap Carousel 的行为与我预期的一样(点击时 prev/next 控制前进图像)。

不幸的是,进行更改会破坏网页底部的其他轮播功能 (caroufredsel)(即,不是在 caroufredsel 中一次仅显示 3 个元素,而是显示所有项目和 caroufredsel 的控件然后不工作)。我真的需要在 $(document).ready 功能中包装其他 jQuery 代码......但是当我这样做时,Bootstrap prev/next 控件无法正常工作。

有人对这里发生的事情以及如何解决它有任何建议吗? 这是 jet.js 文件的完整版本:

function scroll_to(clicked_link, nav_height) {
    var element_class = clicked_link.attr('href').replace('#', '.');
    var scroll_to = 0;
    if(element_class != '.top-content') {
        element_class += '-container';
        scroll_to = $(element_class).offset().top - nav_height;
    }
    if($(window).scrollTop() != scroll_to) {
        $('html, body').stop().animate({scrollTop: scroll_to}, 1000);
    }
}


$(document).ready(function() {
// Bootstrap Carousel -- Tried each of the following lines but neither of them helped
// $('#carousel-generic-example').carousel()
// $('.carousel').carousel()
// $('#carousel-generic-example').carousel()});
// {
    // 'prev'
    // 'next'
    // pause: true,
    // interval: false,
    // keyboard: true
// }

// jQuery('#carousel-generic-example').carousel();

// Pretty photo script
$("a[data-rel^='prettyPhoto']").prettyPhoto({
        theme: 'light_square',
        social_tools: false,
        hook: 'data-rel'
});


// ------------------------------------------------------------------------------------------
  // Code below attempted to dynamically change glyphicons used on web page separator
  // to avoid having to distinct CSS code for every separator (e.g., blog-separator, project-separator, etc)
  // Unfortunately I couldn't get this to work...this code displays the character string
  // for the blog glyphicon (i.e., e043) rather than the actual glyphicon. StackOverflow (http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-such-as-before-and-after-using-jquery?lq=1) from Blazemonger (#3) suggest it may only work for strings (maybe not hex values)
  // So I'm assuming i can't dynamically insert glyphicons.
// ------------------------------------------------------------------------------------------
  // var regExp = /\#([a-z]+)/;
  //
  //  $(".menu-items a").on('click', function () {
  //     var href = $(this).attr('href');
  //     var matches = regExp.exec(href);
  //     switch(matches[1]) {
  //       case "home":
  //         alert(href);
  //
  //         break;
  //       case "about":
  //         alert(href);
  //         break;
  //       case "projects":
  //         alert(href);
  //         break;
  //       case "blog":
  //         $('.separator-line').attr('data-content', '\e043');
  //         // $(this).attr('data-content', '\e043');
  //         // $(".separator-line::after.content").attr('glyphicon-code',"\e043");
  //         var separatorCode = $(this).attr('data-content', '\e043').val();
  //         alert(separatorCode);
  //         break;
  //       case "contact":
  //         alert(href)
  //         break;
  //     }
  //    });
// -------------------------------------------------------------------------------

// Portfolio Javascript to load images

// var $container = $('.container');
//
// $container.imagesLoaded( function() {
//   $container.masonry({
//     itemSelector        : '.post-box',
//     columnWidth         : '.post-box',
//     transitionDuration  : 0
//   });
// });

$(".truncateIt").dotdotdot({
        // configuration goes here
        /*  The text to add as ellipsis. */
    ellipsis    : '... ',

    /*  How to cut off the text/html: 'word'/'letter'/'children' */
    wrap        : 'word',

    /*  Wrap-option fallback to 'letter' for long words */
    fallbackToLetter: true,

    /*  jQuery-selector for the element to keep and put after the ellipsis. */
    after       : 'a.next',

    /*  Whether to update the ellipsis: true/'window' */
    watch       : false,

    /*  Optionally set a max-height, if null, the height will be measured. */
    height      : 60,

    /*  Deviation for the height-option. */
    tolerance   : 0,

    /*  Callback function that is fired after the ellipsis is added,
        receives two parameters: isTruncated(boolean), orgContent(string). */
    callback    : function( isTruncated, orgContent ) {},

    lastCharacter   : {

        /*  Remove these characters from the end of the truncated text. */
        remove      : [ ' ', ',', ';', '.', '!', '?' ],

        /*  Don't add an ellipsis if this array contains
            the last character of the truncated text. */
        noEllipsis  : []
    }
});

// Scroll location for buttons on banner page

$('a.scroll-link').on('click', function(e) {
  e.preventDefault();
  scroll_to($(this), $('nav').outerHeight());
});

// Link and activate WOW.js
new WOW().init();

$(".nav a").on("click", function(){
   $(".nav").find(".active").removeClass("active");
   $(this).parent().addClass("active");
});

// Smooth scrolling logic

  $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
          || location.hostname == this.hostname) {

          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
             if (target.length) {
               $('html,body').animate({
                   scrollTop: target.offset().top
              }, 1000);
              return false;
          }
      }
  });


    $(".cnbox").each(function () {
        var nheight = $(this).find(".nbox").height();
        $(this).find(".cbox").css("height", nheight + 50);
    });

}); // /document.ready()

var caroufredsel = function () {
        $('#caroufredsel-portfolio-container').carouFredSel({
            responsive: true,
            scroll: 1,
            circular: false,
            infinite: false,
            items: {
                    visible: {
                            min: 1,
                            max: 3
                    }
            },
            prev: '#portfolio-prev',
            next: '#portfolio-next',
            auto: {
                    play: false
            }
    });


    $('#caroufredsel-blog-posts-container').carouFredSel({
        responsive: true,
        scroll: 1,
        circular: false,
        infinite: false,
        items: {
            visible: {
                    min: 1,
                    max: 3
                }
        },
        prev: '#blog-posts-prev',
        next: '#blog-posts-next',
        auto: {
                play: false
        }
    });
};


// Isotope Portfolio
var $container = $('.portfolio-container');
var $blogcontainer = $('.posts-wrap');
var $filter = $('.portfolio-filter');

$(window).load(function () {
        // Bootstrap Carousel -- Tried each of the following lines but neither of them helped
        // jQuery('.carousel').carousel();
        // jQuery('#carousel-generic-example').carousel();

        caroufredsel();
        // Initialize Isotope
        $container.isotope({
                itemSelector: '.portfolio-item-wrapper'
        });

        $blogcontainer.isotope({
                itemSelector: '.article-wrap'
        });

        $('.portfolio-filter a').click(function () {
                var selector = $(this).attr('data-filter');
                $container.isotope({ filter: selector });
                return false;
        });
        $filter.find('a').click(function () {
                $filter.find('a').parent().removeClass('active');
                $(this).parent().addClass('active');
        });
    });

    $(window).smartresize(function () {
        $container.isotope('reLayout');
        $blogcontainer.isotope('reLayout');
    });

    $(window).resize(function () {
        caroufredsel();
    });

干杯。

【问题讨论】:

  • 我不能 100% 确定这一点,但您可以尝试在 gemfile 中关闭 turbolinks(将其注释掉)并再次运行。如果它在这之后工作,解决方案很简单。
  • Swards,感谢您的建议...根据您的建议,我注释掉了 turbolinks(并在 app/views/layouts/application.html.erb 文件中注释掉了对它的“引用”并重新启动了我的Rails 服务器。它确实有效果,但不幸的是,现在 prev/next 控件在初始加载或重新加载时不起作用......但我认为我的问题可能是这样的......即,特定于 Rails。那是说关闭 turbolinks 确实可以让我的其他轮播 (caroufredsel) 在第一次加载时正常工作(以前它只有在我重新加载网页时才能正常工作)。进一步的想法?
  • 您可以对此进行更多搜索 - 但本质上您不想将 $(document).ready 与 turbolinks 一起使用。让你开始stackoverflow.com/questions/18770517/…
  • Swards,谢谢...我会研究这个...也许现在是我更好地理解 $(document).ready 与 $(window).load(function()) 的时候了。我怀疑我的问题是由 Rails 引起的......也许按照您提供的线程将引导我找到解决方案。再次感谢您的回复!
  • 有谁知道 Bootsrap Carousel 是否需要您使用任何 jquery 才能使控件正常工作? (例如,$('#carousel-generic-example).carousel())。

标签: ruby-on-rails twitter-bootstrap carousel


【解决方案1】:

经过多次反复试验,我通过反复试验找到了解决方案。事实证明,$(document).ready(function() { 必须关闭(即,}); 紧接在平滑滚动逻辑之前(即以 $('a[href*=#]:not([href=#])').click(function() { 开头的代码)。

我不完全确定为什么“关闭”必须放在那里,而不是在平滑滚动逻辑之后。

如果有人有解释,我很想听听为什么...正如我所提到的,我主要通过反复试验发现了解决方案。

【讨论】:

    【解决方案2】:

    Bootstrap 通常需要一个 JQuery 文件来克服这个错误。因此,最好将其嵌入到您的文件中,并且它可以在线运行。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2011-10-20
      相关资源
      最近更新 更多