Почему иногда меню аккордеон раскрывается при обновлении страницы

(Ответов: 25, Просмотров: 3164)
Страница 1 из 3 123 Последняя
  1. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    На сайте http://fr3809bb.bget.ru/ при переходе из слайдера сверху на новость, сначала на секунду раскрывается меню, а потом опять сворачивается или при обновлении страницы. Вот скрин Нажмите на изображение для увеличения.  Название:	menu.jpg  Просмотров:	2  Размер:	77.9 Кб  ID:	13333Меню аккордеон (раскрывается при нажатии с появлением подпунктов и закрывается при щелчке обратно).
    Вот так подключил js отвечающий за это в head.php
    PHP код:
    <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/menu.js"></script>
    Само содержимое файла menu.js
    PHP код:
    jQuery.fn.initMenu = function() {  
        return 
    this.each(function(){
            var 
    theMenu = $(this).get(0);
            $(
    '.sub-menu'this).hide();
            $(
    'li.expand > .sub-menu'this).show();
            $(
    'li.expand > .sub-menu'this).prev().addClass('active');
            $(
    'li a'this).click(
                function(
    e) {
                    
    e.stopImmediatePropagation();
                    var 
    theElement = $(this).next();
                    var 
    parent this.parentNode.parentNode;
                    if($(
    parent).hasClass('noaccordion')) {
                        if(
    theElement[0] === undefined) {
                            
    window.location.href this.href;
                        }
                        $(
    theElement).slideToggle('normal', function() {
                            if ($(
    this).is(':visible')) {
                                $(
    this).prev().addClass('active');
                            }
                            else {
                                $(
    this).prev().removeClass('active');
                            }    
                        });
                        return 
    false;
                    }
                    else {
                        if(
    theElement.hasClass('sub-menu') && theElement.is(':visible')) {
                            if($(
    parent).hasClass('menu')) {
                                $(
    '.sub-menu:visible'parent).first().slideUp('normal'
                                function() {
                                    $(
    this).prev().removeClass('active');
                                }
                            );
                            return 
    false;  
                        }
                        return 
    false;
                    }
                    if(
    theElement.hasClass('sub-menu') && !theElement.is(':visible')) {         
                        $(
    '.sub-menu:visible'parent).first().slideUp('normal', function() {
                            $(
    this).prev().removeClass('active');
                        });
                        
    theElement.slideDown('normal', function() {
                            $(
    this).prev().addClass('active');
                        });
                        return 
    false;
                    }
                }
            }
        );
    });
    };

    $(
    document).ready(function() {$('.menu').initMenu();}); 
    В чем может быть проблема? Файл взял готовый в сети. Изменил переменные под себя.
    Последний раз редактировалось SergeyNetIt; 16.01.2014 в 15:56.
    • 0
  2. Sunshine reggae Аватар для OKyJIucT
    • Регистрация: 02.09.2011
    • Сообщений: 3,240
    • Репутация: 1830
    • Webmoney BL: ?
    Попробуйте перенести этот код в конец -поставьте его перед </body>
    • 0
  3. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    OKyJIucT,Подключение самого скрипта
    PHP код:
    <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/menu.js"></script>
    перенести вниз? Я перенес скритп этот вниз - не чего не поменялось. Помигивает. Вот Нажмите на изображение для увеличения.  Название:	menu.jpg  Просмотров:	2  Размер:	77.9 Кб  ID:	13332 А потом опять сворачивается.
    Последний раз редактировалось SergeyNetIt; 16.01.2014 в 15:55.
    • 0
  4. Sapienti sat Аватар для brainix
    • Регистрация: 01.01.2013
    • Сообщений: 1,925
    • Записей в дневнике: 1
    • Репутация: 817
    • Webmoney BL: ?
    SergeyNetIt, в css пропишите скрытие пунктов меню, чтобы без скрипта меню было закрыто как нужно. Скорее всего дело в этом - когда страница загружается, то по стилям меню открыто и только потом оно закрывается скриптом.
    • 0
  5. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    brainix,я скрыл подпункты меню с помощью css, но теперь скрипт не работает. При щелчке меню не раскрывается. Помогите, пожалуйста. Вот, то что относится к меню
    /*Оформление самого левого меню подпунктов Навигация*/
    /*Меню*/
    .menu{
    width:200px;
    margin:0 auto;
    /*background:url(./img/bg_menu_left.jpg);*/
    background-color: #37acb0;
    font: 12px Arial;
    color: #fff !important;
    }
    ul.menu, ul.menu ul {
    list-style-type:none;
    margin: 0;
    padding: 0;
    }

    ul.menu a {
    display: block;
    text-decoration: none;
    text-align: left;
    }

    ul.menu li {
    margin-top: 1px;
    }

    ul.menu li a, ul.menu ul.menu li a {
    padding: 0.5em;
    color: #fff;
    background: #33cbeb;
    }

    ul.menu li a:hover, ul.menu ul.menu li a:hover {
    /* фон и градиент пунктов меню при наведении */
    background: #169ce1;
    }
    /*Подпункты меню без наведения*/
    ul.menu li ul li a, ul.menu ul.menu li ul li a {
    background: #fff;
    color: #000;
    padding-left: 20px;
    display: none; /*скрыл подпункты меню*/
    }
    /*При наведение на подпункты меню*/
    ul.menu li ul li a:hover, ul.menu ul.menu li ul li a:hover {
    background: #f3ebeb;
    border-left: 2px #7caa2d solid;
    border-right: 2px #7caa2d solid;
    padding-left: 18px;
    }
    ul.menu ul.menu li a:hover {
    border-left: 0;
    padding-left: 0.5em;
    }
    ul.menu ul.menu {
    border-left: 5px #f00 solid;
    }
    ul.menu a.active, ul.menu ul.menu li a.active, ul.menu a.active:hover, ul.menu ul.menu li a.active:hover {
    /* фон и градиент активных пунктов меню */
    text-decoration: none;
    color: #faddde;
    background: #7caa2d;
    }
    div.panel {
    border: 1px #000 solid;
    padding: 5px;
    margin-top: 1px;
    }

    ul.menu div.panel a, ul.menu div.panel li a:hover {
    display :inline;
    color: #666;
    background: none;
    margin: 0;
    padding: 0;
    border: none;
    font-weight: bold;
    }
    ul.menu div.panel a:hover {
    color: #000;
    text-decoration: underline;
    }
    .bottom-menu{
    width:200px;
    height:20px;
    /*background:url(./img/bottom_menu.jpg);*/
    background: url(./img/content-sprite.png) 0 -86px;
    }
    /*Конец меню*/
    А теперь как мне с помощью верхнего скрипта menu.js сделать, чтобы меню открывалось и подпункты появлялись. А то они скрыты.
    Последний раз редактировалось SergeyNetIt; 16.01.2014 в 16:52.
    • 0
  6. Sapienti sat Аватар для brainix
    • Регистрация: 01.01.2013
    • Сообщений: 1,925
    • Записей в дневнике: 1
    • Репутация: 817
    • Webmoney BL: ?
    SergeyNetIt, столько кода скрывайте в спойлер.

    Попробуйте тогда прописывать в цсс что скрывать беря прямо из скрипта. Т.е. где в скрипте есть .show() для этого тега в цсс делать скрытие.
    На примере: $('li.expand > .sub-menu', this).show(); в цсс написать li.expand > .sub-menu {display:none;}
    Хотя про валидность такого цсс ничего сказать не могу, я не использую такие сложности ">"
    • 0
  7. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    brainix,прописал, да, меню начало открывается с подпунктами, то все равно эффект тот же с миганием
    При чем заметил только что, что если убрать подключение js слайдера, то мигание пропадает
    Вот его код
    PHP код:
    (function( window, $, undefined ) {
        
        
    // http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
        
    $.fn.touchwipe = function(settings) {
            
            var 
    config = {
                
    min_move_x20,
                
    min_move_y20,
                
    wipeLeft: function() { },
                
    wipeRight: function() { },
                
    wipeUp: function() { },
                
    wipeDown: function() { },
                
    preventDefaultEventstrue
            
    };
         
            if (
    settings) $.extend(configsettings);
     
            
    this.each(function() {
                var 
    startX;
                var 
    startY;
                var 
    isMoving false;

                function 
    cancelTouch() {
                    
    this.removeEventListener('touchmove'onTouchMove);
                    
    startX null;
                    
    isMoving false;
                }    
             
                function 
    onTouchMove(e) {
                    if(
    config.preventDefaultEvents) {
                        
    e.preventDefault();
                    }
                    if(
    isMoving) {
                        var 
    e.touches[0].pageX;
                        var 
    e.touches[0].pageY;
                        var 
    dx startX x;
                        var 
    dy startY y;
                        if(
    Math.abs(dx) >= config.min_move_x) {
                            
    cancelTouch();
                            if(
    dx 0) {
                                
    config.wipeLeft();
                            }
                            else {
                                
    config.wipeRight();
                            }
                        }
                        else if(
    Math.abs(dy) >= config.min_move_y) {
                            
    cancelTouch();
                            if(
    dy 0) {
                                
    config.wipeDown();
                            }
                            else {
                                
    config.wipeUp();
                            }
                        }
                    }
                }
             
                function 
    onTouchStart(e)
                {
                    if (
    e.touches.length == 1) {
                        
    startX e.touches[0].pageX;
                        
    startY e.touches[0].pageY;
                        
    isMoving true;
                        
    this.addEventListener('touchmove'onTouchMovefalse);
                    }
                }         
                if (
    'ontouchstart' in document.documentElement) {
                    
    this.addEventListener('touchstart'onTouchStartfalse);
                }
            });
     
            return 
    this;
        };
        
        $.
    elastislide = function( optionselement ) {
            
    this.$el    = $( element );
            
    this._initoptions );
        };
        
        $.
    elastislide.defaults         = {
            
    speed        450,    // animation speed
            
    easing        '',    // animation easing effect
            
    imageW        105,    // the images width
            
    margin        15,    // image margin right
            
    border        2,    // image border
            
    minItems    1,    // the minimum number of items to show. 
                                // when we resize the window, this will make sure minItems are always shown 
                                // (unless of course minItems is higher than the total number of elements)
            
    current        0,    // index of the current item
                                // when we resize the window, the carousel will make sure this item is visible 
            
    onClick        : function() { return false; } // click item callback
        
    };
        
        $.
    elastislide.prototype = {
            
    _init : function( options ) {
                
                
    this.options = $.extendtrue, {}, $.elastislide.defaultsoptions );
                
                
    // <ul>
                
    this.$sliderthis.$el.find('ul');
                
                
    // <li>
                
    this.$items    this.$slider.children('li');
                
                
    // total number of elements / images
                
    this.itemsCount    this.$items.length;
                
                
    // cache the <ul>'s parent, since we will eventually need to recalculate its width on window resize
                
    this.$esCarouselthis.$slider.parent();
                
                
    // validate options
                
    this._validateOptions();
                
                
    // set sizes and initialize some vars...
                
    this._configure();
                
                
    // add navigation buttons
                
    this._addControls();
                
                
    // initialize the events
                
    this._initEvents();
                
                
    // show the <ul>
                
    this.$slider.show();
                
                
    // slide to current's position
                
    this._slideToCurrentfalse );
                
            },
            
    _validateOptions: function() {
            
                if( 
    this.options.speed )
                    
    this.options.speed 450;
                if( 
    this.options.margin )
                    
    this.options.margin 4;
                if( 
    this.options.border )
                    
    this.options.border 1;
                if( 
    this.options.minItems || this.options.minItems this.itemsCount )
                    
    this.options.minItems 1;
                if( 
    this.options.current this.itemsCount )
                    
    this.options.current 0;
                    
            },
            
    _configure: function() {
                
                
    // current item's index
                
    this.currentthis.options.current;
                
                
    // the ul's parent's (div.es-carousel) width is the "visible" width
                
    this.visibleWidththis.$esCarousel.width();
                
                
    // test to see if we need to initially resize the items
                
    if( this.visibleWidth this.options.minItems * ( this.options.imageW this.options.border ) + ( this.options.minItems ) * this.options.margin ) {
                    
    this._setDim( ( this.visibleWidth - ( this.options.minItems ) * this.options.margin ) / this.options.minItems );
                    
    this._setCurrentValues();
                    
    // how many items fit with the current width
                    
    this.fitCount    this.options.minItems;
                }
                else {
                    
    this._setDim();
                    
    this._setCurrentValues();
                }
                
                
    // set the <ul> width
                
    this.$slider.css({
                    
    width    this.sliderW
                
    });
                
            },
            
    _setDim    : function( elW ) {
                
                
    // <li> style
                
    this.$items.css({
                    
    marginRight    this.options.margin,
                    
    width: ( elW ) ? elW this.options.imageW this.options.border
                
    }).children('a').css({ // <a> style
                    
    borderWidth        this.options.border
                
    });
                
            },
            
    _setCurrentValues: function() {
                
                
    // the total space occupied by one item
                
    this.itemWthis.$items.outerWidth(true);
                
                
    // total width of the slider / <ul>
                // this will eventually change on window resize
                
    this.sliderWthis.itemW this.itemsCount;
                
                
    // the ul parent's (div.es-carousel) width is the "visible" width
                
    this.visibleWidththis.$esCarousel.width();
                
                
    // how many items fit with the current width
                
    this.fitCountMath.floorthis.visibleWidth this.itemW );
                
            },
            
    _addControls: function() {
                
                
    this.$navNext= $('<span class="es-nav-next">Next</span>');
                
    this.$navPrev= $('<span class="es-nav-prev">Previous</span>');
                $(
    '<div class="es-nav"/>')
                .
    appendthis.$navPrev )
                .
    appendthis.$navNext )
                .
    appendTothis.$el );
                
                
    //this._toggleControls();
                    
            
    },
            
    _toggleControls    : function( dirstatus ) {
                
                
    // show / hide navigation buttons
                
    if( dir && status ) {
                    if( 
    status === )
                        ( 
    dir === 'right' ) ? this.$navNext.show() : this.$navPrev.show();
                    else
                        ( 
    dir === 'right' ) ? this.$navNext.hide() : this.$navPrev.hide();
                }
                else if( 
    this.current === this.itemsCount || this.fitCount >= this.itemsCount )
                        
    this.$navNext.hide();
                
            },
            
    _initEvents    : function() {
                
                var 
    instancethis;
                
                
    // window resize
                
    $(window).bind('resize.elastislide', function( event ) {
                    
                    
    // set values again
                    
    instance._setCurrentValues();
                    
                    
    // need to resize items
                    
    if( instance.visibleWidth instance.options.minItems * ( instance.options.imageW instance.options.border ) + ( instance.options.minItems ) * instance.options.margin ) {
                        
    instance._setDim( ( instance.visibleWidth - ( instance.options.minItems ) * instance.options.margin ) / instance.options.minItems );
                        
    instance._setCurrentValues();
                        
    instance.fitCount    instance.options.minItems;
                    }    
                    else{
                        
    instance._setDim();
                        
    instance._setCurrentValues();
                    }
                    
                    
    instance.$slider.css({
                        
    widthinstance.sliderW 10 // TODO: +10px seems to solve a firefox "bug" :S
                    
    });
                            
                    
    // slide to the current element
                    
    clearTimeoutinstance.resetTimeout );
                    
    instance.resetTimeout    setTimeout(function() {
                        
    instance._slideToCurrent();
                    }, 
    200);
                    
                });
                
                
    // navigation buttons events
                
    this.$navNext.bind('click.elastislide', function( event ) {
                    
    instance._slide('right');
                });
                
                
    this.$navPrev.bind('click.elastislide', function( event ) {
                    
    instance._slide('left');
                });
                
                
    // item click event
                
    this.$items.bind('click.elastislide', function( event ) {
                    
    instance.options.onClick( $(this) );
                    return 
    true;//Включить или отключить переход по ссылкам
                
    });
                
                
    // touch events
                
    instance.$slider.touchwipe({
                    
    wipeLeft            : function() {
                        
    instance._slide('right');
                    },
                    
    wipeRight            : function() {
                        
    instance._slide('left');
                    }
                });
                
            },
            
    _slide: function( dirvalanimcallback ) {
                
                
    // if animating return
                
    if( this.$slider.is(':animated') )
                    return 
    false;
                
                
    // current margin left
                
    var mlparseFloatthis.$slider.css('margin-left') );
                
                
    // val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function)
                
    if( val === undefined ) {
                
                    
    // how much to slide?
                    
    var amount    this.fitCount this.itemWval;
                    
                    if( 
    amount ) return false;
                    
                    
    // make sure not to leave a space between the last item / first item and the end / beggining of the slider available width
                    
    if( dir === 'right' && this.sliderW - ( Math.absml ) + amount ) < this.visibleWidth ) {
                        
    amount    this.sliderW - ( Math.absml ) + this.visibleWidth ) - this.options.margin// decrease the margin left
                        // show / hide navigation buttons
                        
    this._toggleControls'right', -);
                        
    this._toggleControls'left');
                    }
                    else if( 
    dir === 'left' && Math.absml ) - amount ) {                
                        
    amount    Math.absml );
                        
    // show / hide navigation buttons
                        
    this._toggleControls'left', -);
                        
    this._toggleControls'right');
                    }
                    else {
                        var 
    fml// future margin left
                        
    dir === 'right' 
                            ? 
    fml Math.absml ) + this.options.margin Math.absamount 
                            : 
    fml Math.absml ) - this.options.margin Math.absamount );
                        
                        
    // show / hide navigation buttons
                        
    if( fml )
                            
    this._toggleControls'left');
                        else    
                            
    this._toggleControls'left', -);
                        
                        if( 
    fml this.sliderW this.visibleWidth )
                            
    this._toggleControls'right');
                        else    
                            
    this._toggleControls'right', -);
                            
                    }
                    
                    ( 
    dir === 'right' ) ? val '-=' amount val '+=' amount
                    
                
    }
                else {
                    var 
    fml    Math.absval ); // future margin left
                    
                    
    if( Math.maxthis.sliderWthis.visibleWidth ) - fml this.visibleWidth ) {
                        
    val    = - ( Math.maxthis.sliderWthis.visibleWidth ) - this.visibleWidth );
                        if( 
    val !== )
                            
    val += this.options.margin;    // decrease the margin left if not on the first position
                            
                        // show / hide navigation buttons
                        
    this._toggleControls'right', -);
                        
    fml    Math.absval );
                    }
                    
                    
    // show / hide navigation buttons
                    
    if( fml )
                        
    this._toggleControls'left');
                    else
                        
    this._toggleControls'left', -);
                    
                    if( 
    Math.maxthis.sliderWthis.visibleWidth ) - this.visibleWidth fml this.options.margin )    
                        
    this._toggleControls'right');
                    else
                        
    this._toggleControls'right', -);
                        
                }
                
                $.
    fn.applyStyle = ( anim === undefined ) ? $.fn.animate : $.fn.css;
                
                var 
    sliderCSS= { marginLeft val };
                
                var 
    instancethis;
                
                
    this.$slider.applyStylesliderCSS, $.extendtrue, [], { duration this.options.speedeasing this.options.easingcomplete : function() {
                    if( 
    callback callback.call();
                } } ) );
                
            },
            
    _slideToCurrent: function( anim ) {
                
                
    // how much to slide?
                
    var amount    this.current this.itemW;
                
    this._slide('', -amountanim );
                
            },
            
    add    : function( $newelemscallback ) {
                
                
    // adds new items to the carousel
                
    this.$items this.$items.add$newelems );
                
    this.itemsCount    this.$items.length;
                
    this._setDim();
                
    this._setCurrentValues();
                
    this.$slider.css({
                    
    width    this.sliderW
                
    });
                
    this._slideToCurrent();
                
                if ( 
    callback callback.call$newelems );
                
            },
            
    destroy    : function( callback ) {
                
    this._destroycallback );
            },
            
    _destroy : function( callback ) {
                
    this.$el.unbind('.elastislide').removeData('elastislide');
                $(
    window).unbind('.elastislide');
                if ( 
    callback callback.call();
            }
        };
        
        var 
    logError = function( message ) {
            if ( 
    this.console ) {
                
    console.errormessage );
            }
        };
        
        $.
    fn.elastislide = function( options ) {
            if ( 
    typeof options === 'string' ) {
                var 
    args = Array.prototype.slice.callarguments);

                
    this.each(function() {
                    var 
    instance = $.datathis'elastislide' );
                    if ( !
    instance ) {
                        
    logError"cannot call methods on elastislide prior to initialization; " +
                        
    "attempted to call method '" options "'" );
                        return;
                    }
                    if ( !$.
    isFunctioninstance[options] ) || options.charAt(0) === "_" ) {
                        
    logError"no such method '" options "' for elastislide instance" );
                        return;
                    }
                    
    instanceoptions ].applyinstanceargs );
                });
            } 
            else {
                
    this.each(function() {
                    var 
    instance = $.datathis'elastislide' );
                    if ( !
    instance ) {
                        $.
    datathis'elastislide', new $.elastislideoptionsthis ) );
                    }
                });
            }
            return 
    this;
        };
        
    })( 
    windowjQuery ); 
    Наверное из за него. А что в нем не так. Код стандартный.
    Последний раз редактировалось SergeyNetIt; 16.01.2014 в 17:22.
    • 0
  8. Дипломник Аватар для _Серега_
    • Регистрация: 12.02.2013
    • Сообщений: 125
    • Репутация: 32
    • Webmoney BL: ?
    код скрипта ужасен, для аккордеона надо то 5 строчек возьмите мой тут для меню навигации в левой колонке http://jsfiddle.net/codeffeiner/2KJmr/
    • 0
  9. Опытный
    • Регистрация: 06.08.2013
    • Сообщений: 307
    • Репутация: 5
    _Серега_,а как сделать, чтобы при щелчке обратно на пункт меню он закрывался?
    • 0
  10. Дипломник Аватар для _Серега_
    • Регистрация: 12.02.2013
    • Сообщений: 125
    • Репутация: 32
    • Webmoney BL: ?
    SergeyNetIt, добавилось условие else проапдейтил на фидле
    PHP код:
    $(function initMenu() {
        $(
    '.nav ul').hide();
        $(
    '.nav li.kind b').click(function (e) {
            var 
    checkElement;
            
    checkElement = $(this).next();
            if ((
    checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                
    e.preventDefault();
                $(
    '.nav ul:visible').slideUp('slow');
                
    checkElement.slideDown();
            } else {
                
    e.preventDefault();
                
    checkElement.slideUp('slow');
            }
        });
    }); 
    Последний раз редактировалось _Серега_; 16.01.2014 в 21:23.
    • 1

    Спасибо сказали:

    SergeyNetIt(16.01.2014),
Страница 1 из 3 123 Последняя

Похожие темы

Темы Раздел Ответов Последний пост
Почему сайдбар с меню не корректно отображается в IE8
WordPress 1 24.12.2013 14:07
Почему на старом сайте новые страницы попадают в сопли?
Общие вопросы поисковой оптимизации 5 31.10.2013 12:47
Нужно немного изменить скрипт аккордеон-меню
Софт, скрипты, сервисы 2 20.03.2012 01:01
Ссыла из рубрики в меню страницы сайта
Web программирование 5 28.02.2012 02:58

У кого попросить инвайт?

Вы можете попросить инвайт у любого модератора:

Информеры