Конфликт между Smoothscroll.js и Bootstrap Carousel

Я использую Smoothscroll.js (не использую GEM — см. ссылку на код ниже) на своей странице приветствия, чтобы пользователи могли переходить в соответствующий раздел веб-страницы приветствия с помощью фиксированных пунктов меню Bootstrap Navbar. На отдельной странице я использую Bootstrap Carousel, чтобы позволить пользователю просматривать отдельные элементы портфолио (показать страницу).

Это позволяет пользователю щелкнуть пункт меню «Портфолио» на панели навигации на странице приветствия, чтобы плавно перейти к разделу «Портфолио» на странице приветствия. Затем пользователь может щелкнуть конкретный элемент портфолио на странице приветствия, и он перейдет на страницу показа этого конкретного элемента портфолио, где он сможет увидеть несколько изображений для этого элемента портфолио с помощью карусели Bootstrap.

Проблема в том, что если я включу логику Smoothscroll в область действия $(document).ready () в моем файле app/assets/javascripts/jet.js (см. ниже), элементы управления prev/next в карусели BootStrap на странице show не будут реагировать на клики пользователя.

Если я редактирую файл jet.js и помещаю логику Smoothscroll вне области действия функции $(document).ready (), сохраняю эти изменения и затем загружаю свой веб-сайт. Все работает отлично. Smoothscroll работает, как и ожидалось, на странице приветствия, а элементы управления «предыдущий/следующий» отлично работают на странице показа портфолио. Я могу свободно перемещаться между двумя страницами (приветствие и страница показа портфолио), и все продолжает работать. Однако, если я перезагружу веб-страницу и попытаюсь выбрать элемент Navbar на странице приветствия для плавной прокрутки к любому разделу на странице приветствия, я получу ошибку маршрутизации (например, маршрут не соответствует [GET] "/index.html").

FYI... моя среда разработки:

  • Рельсы 4.2.1
  • Использование всех последних версий jQuery (v2.1.3), Bootstrap (v3.3.5)
  • Используя (логику Smoothscroll.js), см. файл jet.js ниже
  • Руби v2.1.5
  • Turbolinks отключен (удален из GEMfile и удалены другие рефы)

Итак, у меня есть два связанных вопроса:

1) Любая идея, почему Smoothscroll.js блокирует правильную работу элементов управления prev/next, когда Smoothscroll включен в область действия функции $(document).ready()?

2) Мне интересно, почему все работает нормально, когда я вношу изменения (т.е. размещаю логику smoothscroll.js за пределами $(document).ready), а затем загружаю страницу с этими изменениями, но все же, когда я перезагружаю веб page во второй раз я получаю сообщение об ошибке маршрутизации. Как будто места плавной прокрутки кэшируются при первой загрузке, но не при второй загрузке (как отмечалось выше)?

Для справки вот файл jet.js:

$(document).ready(function() {

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


$(".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  : []
    }
});



// WOW Reveals CSS animation as you scroll down a page.
// Link and activate WOW.js
new WOW().init();

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

$('#carousel-generic-example').carousel({
        interval:2000,
        pause: "false"
});
$('#playButton').click(function () {
        $('#carousel-generic-example').carousel('cycle');
});
$('#pauseButton').click(function () {
        $('#carousel-generic-example').carousel('pause');
});

}); // /document.ready()

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);
    }
}

// Scroll location for buttons on banner page
$('a.scroll-link').on('click', function(e) {
  e.preventDefault();
  scroll_to($(this), $('nav').outerHeight());
});

// Smooth Scrolling for anchor links: http://www.billerickson.net/code/smooth-scrolling-anchor-links/
  $('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;
          }
      }
  });

// }); // /document.ready()


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



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();
    });

});

К вашему сведению, вот мой файл app/assets/javascripts/application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .

person user2101068    schedule 22.08.2015    source источник


Ответы (2)


У меня была такая же проблема, но я нашел файлы JS (jss-script.js и jss-script.min.js) в папке плагинов, поэтому я изменил селектор HTML только на один div по идентификатору и каждый <a> с href="#" в нем. Измените значения в обоих файлах.

/****************************************************
 *                                                  *
 *      JUMP TO ANCHOR LINK SCRIPT START            *
 *                                                  *
 ****************************************************/
 /*SSB-CONTAINER WAS MY SIDE PANEL MENU*/
  $('#ssb-container a[href*="#"]').click(function() 
  {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
        || location.hostname == this.hostname) 
    {
      
      var target = $(this.hash),
      headerHeight = $(".primary-header").height() + 5; // Get fixed header height
            
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              
      if (target.length) 
      {
        $('html,body').animate({ scrollTop: target.offset().top }, scrollSpeed, scrollStyle );
        return false;
      }
    }
  });
  

И он действительно начал работать!

person Josef    schedule 22.07.2018

Я переключил передачу и использовал следующее решение. решение для плавной прокрутки. Это сработало отлично и было намного проще, чем то, что я пытался сделать.

Я все еще озадачен тем, что конфликт был в моем первоначальном решении. Это заставляет меня думать, что я не понимаю некоторых аспектов того, как все это работает.

Поэтому, если у вас есть идеи или теории, не стесняйтесь добавлять свои комментарии или предлагаемые решения.

person user2101068    schedule 23.08.2015