Не работает выпадающее меню - ошибка jquery.onepagenav.js
Друзья, просто не знаю и какой стороной биться головой об стену... Не работает у меня выпадающее меню на yii2.
Не раскрывается, окояный dropdown в Nav... Причем на главной странице в layout этот же самый dropdown работает, раскрывается и переходит по тем же самым ссылочкам... Bootstrap.js подключён - да и не в нём дело - так как на главной странице то работает. Открыл консоль - при нажатии на ссылку ругается "TypeError: $(...).offset(...) is undefined" в файле "jquery.onepagenav.js" на 202 строке в функции(здесь строка №02): scrollTo: function(target, callback) { var offset = $(target).offset().top; $('html, body').animate({ scrollTop: offset }, this.config.scrollSpeed, this.config.easing, callback); }, unbindInterval: function() { clearInterval(this.t); this.$win.unbind('scroll.onePageNav'); } Сам код виджета: echo \yii\bootstrap\Nav::widget( [ 'activateParents' => true, 'activateItems' => false, 'options' => [ 'class' => 'nav-pills navbar-nav navbar-right main-nav' ], 'items' => [ ['label' => 'Главная', 'url' => ['/']], ['label' => 'Испания', 'items' => [ ['label' => 'Угловые', 'url' => ['play/']], ['label' => 'h2h', 'url' => ['play/champ', 'id' => 1]], ] ], ['label' => 'Англия', 'items' => [ ['label' => 'Угловые', 'url' => ['league/']], ['label' => 'h2h', 'url' => ['play/champ', 'id' => 2]], ] ], ['label' => 'Войти', 'url' => ['site/index']], ], ] Гуглил - были теории о том, что jquery необходимо подключать раньше bootstrap.min.js. Так и подключено: public $js = [ 'js/jquery-1.11.1.min.js', 'js/owl.carousel.min.js', 'js/bootstrap.min.js', 'js/wow.min.js', 'js/typewriter.js', 'js/jquery.onepagenav.js', 'js/main.js', ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapPluginAsset', ]; Дальше пробовал все js-скрипты подключать в голове "Head"! Результаты такие же... Может что-то подскажите? |
Цитата:
|
Ну всё уже каша в голове! Переместил на последнее место!
Вот это в лейауте: </script><script src="/assets/4f094002/jquery.js"></script> <script src="/assets/3ef7f645/yii.js"></script> <script src="/js/jquery-1.11.1.min.js"></script> <script src="/js/owl.carousel.min.js"></script> <script src="/js/wow.min.js"></script> <script src="/js/typewriter.js"></script> <script src="/js/jquery.onepagenav.js"></script> <script src="/js/main.js"></script> <script src="/js/bootstrap.min.js"></script> <script src="/assets/5734c980/js/bootstrap.js"></script> /js/bootstrap.min.js и assets/5734c980/js/bootstrap.js взаимозаменяемы? Можно что-то одно исключить?? |
greengo86,
предположительно так <script src="/js/jquery-1.11.1.min.js"></script> <script src="/assets/3ef7f645/yii.js"></script> <script src="/js/owl.carousel.min.js"></script> <script src="/js/wow.min.js"></script> <script src="/js/typewriter.js"></script> <script src="/js/jquery.onepagenav.js"></script> <script src="/js/main.js"></script> <script src="/assets/5734c980/js/bootstrap.js"></script> |
Спасибо рони, что постарался помочь! Далее еще возникли проблемы с модальным окном, но всё разрешилось редактированием файла AppAsset - методом проб и ошибок(точнее комментированием некоторых строк). Может кому и пригодится:
public $js = [ // 'js/jquery-1.11.1.min.js', 'js/owl.carousel.min.js', 'js/wow.min.js', 'js/typewriter.js', 'js/jquery.onepagenav.js', 'js/main.js', // 'js/bootstrap.min.js', ]; public $depends = [ // 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapPluginAsset', ]; |
Нет! Через какое-то время ошибка снова появилась... Выпадающее меню работает когда скролл находится строго наверху страницы, если прокрутит немного вниз выдаётся в консоли firebug код (привел ниже)! Пробовал откатится по коммитам - бесполезно! Видимо не заметил, что в какой-то момент работать перестало...
В консоли fireBug и ругается на файл - jquery.onepagenav.js : TypeError: $(...).offset(...) is undefined var offset = $(target).offset().top; Вот код jquery.onepagenav.js в той части, где связано со скроллом: scrollChange: function() { var windowTop = this.$win.scrollTop(); var position = this.getSection(windowTop); var $parent; //If the position is set if(position !== null) { $parent = this.$elem.find('a[href$="#' + position + '"]').parent(); //If it's not already the current section if(!$parent.hasClass(this.config.currentClass)) { //Change the highlighted nav item this.adjustNav(this, $parent); //If there is a scrollChange callback if(this.config.scrollChange) { this.config.scrollChange($parent); } } } }, scrollTo: function(target, callback) { var offset = $(target).offset().top; $('html, body').animate({ scrollTop: offset }, this.config.scrollSpeed, this.config.easing, callback); }, unbindInterval: function() { clearInterval(this.t); this.$win.unbind('scroll.onePageNav'); } }; OnePageNav.defaults = OnePageNav.prototype.defaults; $.fn.onePageNav = function(options) { return this.each(function() { new OnePageNav(this, options).init(); }); }; Порядок подключения файлов в проекте yii2 перепробовал самые разные: public $js = [ // 'js/jquery-1.11.1.min.js', 'js/owl.carousel.min.js', 'js/wow.min.js', 'js/typewriter.js', 'js/jquery.onepagenav.js', 'js/main.js', // 'js/bootstrap.min.js', ]; public $depends = [ // 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapPluginAsset' ]; Так до какого-то времени работало :oops: Что-нибудь посоветуете! Весь вечер возился... Воз и ныне там |
greengo86,
замените все $(...) и $. на jQuery() и jQuery. |
Рони, вот так?
... scrollTo: function(target, callback) { var offset = jQuery(target).offset().top; jQuery().animate({ scrollTop: offset }, this.config.scrollSpeed, this.config.easing, callback); }, unbindInterval: function() { clearInterval(this.t); this.$win.unbind('scroll.onePageNav'); } }; OnePageNav.defaults = OnePageNav.prototype.defaults; jQuery.fn.onePageNav = function(options) { return this.each(function() { new OnePageNav(this, options).init(); }); }; })( jQuery, window , document ); Если так, то всё равно не работает |
Заменил во всём документе:
;(function($, window, document, undefined){ // our plugin constructor var OnePageNav = function(elem, options){ this.elem = elem; this.$elem = jQuery(); this.options = options; this.metadata = this.$elem.data('plugin-options'); this.$win = jQuery(); this.sections = {}; this.didScroll = false; this.$doc = jQuery(); this.docHeight = this.$doc.height(); }; // the plugin prototype OnePageNav.prototype = { defaults: { navItems: 'a', currentClass: 'current', changeHash: false, easing: 'swing', filter: '', scrollSpeed: 750, scrollThreshold: 0.5, begin: false, end: false, scrollChange: false }, init: function() { // Introduce defaults that can be extended either // globally or using an object literal. this.config = jQuery.extend({}, this.defaults, this.options, this.metadata); this.$nav = this.$elem.find(this.config.navItems); //Filter any links out of the nav if(this.config.filter !== '') { this.$nav = this.$nav.filter(this.config.filter); } //Handle clicks on the nav this.$nav.on('click.onePageNav', jQuery.proxy(this.handleClick, this)); //Get the section positions this.getPositions(); //Handle scroll changes this.bindInterval(); //Update the positions on resize too this.$win.on('resize.onePageNav', jQuery.proxy(this.getPositions, this)); return this; }, adjustNav: function(self, $parent) { self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass); $parent.addClass(self.config.currentClass); }, bindInterval: function() { var self = this; var docHeight; self.$win.on('scroll.onePageNav', function() { self.didScroll = true; }); self.t = setInterval(function() { docHeight = self.$doc.height(); //If it was scrolled if(self.didScroll) { self.didScroll = false; self.scrollChange(); } //If the document height changes if(docHeight !== self.docHeight) { self.docHeight = docHeight; self.getPositions(); } }, 250); }, getHash: function($link) { return $link.attr('href').split('#')[1]; }, getPositions: function() { var self = this; var linkHref; var topPos; var $target; self.$nav.each(function() { linkHref = self.getHash(jQuery()); $target = jQuery(); if($target.length) { topPos = $target.offset().top; self.sections[linkHref] = Math.round(topPos); } }); }, getSection: function(windowPos) { var returnValue = null; var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold); for(var section in this.sections) { if((this.sections[section] - windowHeight) < windowPos) { returnValue = section; } } return returnValue; }, handleClick: function(e) { var self = this; var $link = jQuery(); var $parent = $link.parent(); var newLoc = '#' + self.getHash($link); if(!$parent.hasClass(self.config.currentClass)) { //Start callback if(self.config.begin) { self.config.begin(); } //Change the highlighted nav item self.adjustNav(self, $parent); //Removing the auto-adjust on scroll self.unbindInterval(); //Scroll to the correct position self.scrollTo(newLoc, function() { //Do we need to change the hash? if(self.config.changeHash) { window.location.hash = newLoc; } //Add the auto-adjust on scroll back in self.bindInterval(); //End callback if(self.config.end) { self.config.end(); } }); } e.preventDefault(); }, scrollChange: function() { var windowTop = this.$win.scrollTop(); var position = this.getSection(windowTop); var $parent; //If the position is set if(position !== null) { $parent = this.$elem.find('a[href$="#' + position + '"]').parent(); //If it's not already the current section if(!$parent.hasClass(this.config.currentClass)) { //Change the highlighted nav item this.adjustNav(this, $parent); //If there is a scrollChange callback if(this.config.scrollChange) { this.config.scrollChange($parent); } } } }, scrollTo: function(target, callback) { var offset = jQuery().offset().top; jQuery().animate({ scrollTop: offset }, this.config.scrollSpeed, this.config.easing, callback); }, unbindInterval: function() { clearInterval(this.t); this.$win.unbind('scroll.onePageNav'); } }; OnePageNav.defaults = OnePageNav.prototype.defaults; jQuery.fn.onePageNav = function(options) { return this.each(function() { new OnePageNav(this, options).init(); }); }; })( jQuery, window , document ); При клике на второй уровень выпадающего списка ни одной ошибки в консоли, но подменю второго уровня всё равно не выезжает =) |
greengo86,
:-? было $('html, body').animate({ почему вместо jQuery('html, body').animate({ у вас jQuery().animate({ |
рони, Потомучто Дебилоид Петрович Я :-/
scrollChange: function() { var windowTop = this.$win.scrollTop(); var position = this.getSection(windowTop); var $parent; //If the position is set if(position !== null) { $parent = this.$elem.find('a[href$="#' + position + '"]').parent(); //If it's not already the current section if(!$parent.hasClass(this.config.currentClass)) { //Change the highlighted nav item this.adjustNav(this, $parent); //If there is a scrollChange callback if(this.config.scrollChange) { this.config.scrollChange($parent); } } } }, scrollTo: function(target, callback) { var offset = jQuery(target).offset().top; jQuery('html, body').animate({ scrollTop: offset }, this.config.scrollSpeed, this.config.easing, callback); }, unbindInterval: function() { clearInterval(this.t); this.$win.unbind('scroll.onePageNav'); } }; OnePageNav.defaults = OnePageNav.prototype.defaults; jQuery.fn.onePageNav = function(options) { return this.each(function() { new OnePageNav(this, options).init(); }); }; })( jQuery, window , document ); Но всё равно не помогает! Спасибо тебе, рони, но уже забил и нашёл другую реализацию... С этой пока не дано разобраться, к сожелению |
Часовой пояс GMT +3, время: 10:54. |