jQuery与另一个jQuery冲突

时间:2012-11-29 22:19:26

标签: jquery conflict

我有一个奇怪的案例,我相信两个jQ​​uery插件彼此冲突:一方面我有一个[ddsmoothmenu] [1]已经工作正常,直到我安装了(WP插件) )Revolution滑块插件。我安装后,菜单停止工作。该插件具有无冲突模式,一旦打开,解决菜单问题,但其他文件/插件的其他jQuery效果停止工作。一种解决方案是替换菜单,但我真的很喜欢它而不愿意(除非绝对必要)。

有什么建议吗?

非常感谢

更新: 这是菜单jQuery:

var ddsmoothmenu={

//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', 'down.gif', 11], right:['rightarrowclass', 'down.gif']},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:false, offsetx:5, offsety:5}, //enable shadow?
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively

detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,
css3support: window.msPerformance || (!document.all && document.querySelector), //detect browsers that support CSS3 box shadows (ie9+ or FF3.5+, Safari3+, Chrome etc)
ismobile:navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i) != null,     //boolean check for popular mobile browsers

getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu
$menucontainer.html("Loading Menu...")
$.ajax({
    url: setting.contentsource[1], //path to external menu file
    async: true,
    error:function(ajaxrequest){
        $menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
    },
    success:function(content){
        $menucontainer.html(content)
        ddsmoothmenu.buildmenu($, setting)
    }
})

},

buildmenu:function($, setting){
var smoothmenu=ddsmoothmenu
var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
var $headers=$mainmenu.find("ul").parent()
$headers.hover(
    function(e){
        $(this).children('a:eq(0)').addClass('selected')
    },
    function(e){
        $(this).children('a:eq(0)').removeClass('selected')
    }
)
$headers.each(function(i){ //loop through each LI header
    var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
    var $subul=$(this).find('ul:eq(0)').css({display:'block'})
    $subul.data('timers', {})
    this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
    this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
    $subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
    $curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
        '<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
        +'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
        + '" style="border:0;" />'
    )
    if (smoothmenu.shadow.enable && !smoothmenu.css3support){ //if shadows enabled and browser doesn't support CSS3 box shadows
        this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
        if (this.istopheader)
            $parentshadow=$(document.body)
        else{
            var $parentLi=$curobj.parents("li:eq(0)")
            $parentshadow=$parentLi.get(0).$shadow
        }
        this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
    }
    $curobj.hover(
        function(e){
            var $targetul=$subul //reference UL to reveal
            var header=$curobj.get(0) //reference header LI as DOM object
            clearTimeout($targetul.data('timers').hidetimer)
            $targetul.data('timers').showtimer=setTimeout(function(){
                header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
                var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
                menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
                if ($targetul.queue().length<=1){ //if 1 or less queued animations
                    $targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
                    if (smoothmenu.shadow.enable && !smoothmenu.css3support){
                        var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
                        var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
                        if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
                            header.$shadow.css({opacity:1})
                        }
                        header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
                    }
                }
            }, ddsmoothmenu.showhidedelay.showdelay)
        },
        function(e){
            var $targetul=$subul
            var header=$curobj.get(0)
            clearTimeout($targetul.data('timers').showtimer)
            $targetul.data('timers').hidetimer=setTimeout(function(){
                $targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
                if (smoothmenu.shadow.enable && !smoothmenu.css3support){
                    if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
                        header.$shadow.children('div:eq(0)').css({opacity:0})
                    }
                    header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
                }
            }, ddsmoothmenu.showhidedelay.hidedelay)
        }
    ) //end hover
}) //end $headers.each()
if (smoothmenu.shadow.enable && smoothmenu.css3support){ //if shadows enabled and browser supports CSS3 shadows
    var $toplevelul=$('#'+setting.mainmenuid+' ul li ul')
    var css3shadow=parseInt(smoothmenu.shadow.offsetx)+"px "+parseInt(smoothmenu.shadow.offsety)+"px 5px #aaa" //construct CSS3 box-shadow value
    var shadowprop=["boxShadow", "MozBoxShadow", "WebkitBoxShadow", "MsBoxShadow"] //possible vendor specific CSS3 shadow properties
    for (var i=0; i<shadowprop.length; i++){
        $toplevelul.css(shadowprop[i], css3shadow)
    }
}
$mainmenu.find("ul").css({display:'none', visibility:'visible'})

},

init:function(setting){
if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
    var mainmenuid='#'+setting.mainmenuid
    var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
    document.write('<style type="text/css">\n'
        +mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
        +mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
    +'</style>')
}
this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
jQuery(document).ready(function($){ //ajax menu?
    if (typeof setting.contentsource=="object"){ //if external ajax menu
        ddsmoothmenu.getajaxmenu($, setting)
    }
    else{ //else if markup menu
        ddsmoothmenu.buildmenu($, setting)
    }
})

}

} //end ddsmoothmenu variable​​

不,我没有加载多个版本的jQuery。我正在通过注册表加载所有jQuery并在WordPress中排队脚本(对不起,如果之前我不清楚,这是一个WordPress站点)。

WordPress Revolution Slider的代码是一个高级插件,所以我不确定我是否可以在这里发布。如果有人能帮我澄清一下,我也非常乐意添加

更新2:经过额外的测试后,冲突的jQuery文件就是这两个(上面和上面这个):

(function($) {
var aux     = {
        // navigates left / right
        navigate    : function( dir, $el, $wrapper, opts, cache ) {

            var scroll      = opts.scroll,
                factor      = 1,
                idxClicked  = 0;

            if( cache.expanded ) {
                scroll      = 1; // scroll is always 1 in full mode
                factor      = 3; // the width of the expanded item will be 3 times bigger than 1 collapsed item 
                idxClicked  = cache.idxClicked; // the index of the clicked item
            }

            // clone the elements on the right / left and append / prepend them according to dir and scroll
            if( dir === 1 ) {
                $wrapper.find('div.ca-item:lt(' + scroll + ')').each(function(i) {
                    $(this).clone(true).css( 'left', ( cache.totalItems - idxClicked + i ) * cache.itemW * factor + 'px' ).appendTo( $wrapper );
                });
            }
            else {
                var $first  = $wrapper.children().eq(0);

                $wrapper.find('div.ca-item:gt(' + ( cache.totalItems  - 1 - scroll ) + ')').each(function(i) {
                    // insert before $first so they stay in the right order
                    $(this).clone(true).css( 'left', - ( scroll - i + idxClicked ) * cache.itemW * factor + 'px' ).insertBefore( $first );
                });
            }

            // animate the left of each item
            // the calculations are dependent on dir and on the cache.expanded value
            $wrapper.find('div.ca-item').each(function(i) {
                var $item   = $(this);
                $item.stop().animate({
                    left    :  ( dir === 1 ) ? '-=' + ( cache.itemW * factor * scroll ) + 'px' : '+=' + ( cache.itemW * factor * scroll ) + 'px'
                }, opts.sliderSpeed, opts.sliderEasing, function() {
                    if( ( dir === 1 && $item.position().left < - idxClicked * cache.itemW * factor ) || ( dir === -1 && $item.position().left > ( ( cache.totalItems - 1 - idxClicked ) * cache.itemW * factor ) ) ) {
                        // remove the item that was cloned
                        $item.remove();
                    }                       
                    cache.isAnimating   = false;
                });
            });

        },
        // opens an item (animation) -> opens all the others
        openItem    : function( $wrapper, $item, opts, cache ) {
            cache.idxClicked    = $item.index();
            // the item's position (1, 2, or 3) on the viewport (the visible items) 
            cache.winpos        = aux.getWinPos( $item.position().left, cache );
            $wrapper.find('div.ca-item').not( $item ).hide();
            $item.find('div.ca-content-wrapper').css( 'left', cache.itemW + 'px' ).stop().animate({
                width   : cache.itemW * 2 + 'px',
                left    : cache.itemW + 'px'
            }, opts.itemSpeed, opts.itemEasing)
            .end()
            .stop()
            .animate({
                left    : '0px'
            }, opts.itemSpeed, opts.itemEasing, function() {
                cache.isAnimating   = false;
                cache.expanded      = true;

                aux.openItems( $wrapper, $item, opts, cache );
            });

        },
        // opens all the items
        openItems   : function( $wrapper, $openedItem, opts, cache ) {
            var openedIdx   = $openedItem.index();

            $wrapper.find('div.ca-item').each(function(i) {
                var $item   = $(this),
                    idx     = $item.index();

                if( idx !== openedIdx ) {
                    $item.css( 'left', - ( openedIdx - idx ) * ( cache.itemW * 3 ) + 'px' ).show().find('div.ca-content-wrapper').css({
                        left    : cache.itemW + 'px',
                        width   : cache.itemW * 2 + 'px'
                    });

                    // hide more link
                    aux.toggleMore( $item, false );
                }
            });
        },
        // show / hide the item's more button
        toggleMore  : function( $item, show ) {
            ( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide(); 
        },
        // close all the items
        // the current one is animated
        closeItems  : function( $wrapper, $openedItem, opts, cache ) {
            var openedIdx   = $openedItem.index();

            $openedItem.find('div.ca-content-wrapper').stop().animate({
                width   : '0px'
            }, opts.itemSpeed, opts.itemEasing)
            .end()
            .stop()
            .animate({
                left    : cache.itemW * ( cache.winpos - 1 ) + 'px'
            }, opts.itemSpeed, opts.itemEasing, function() {
                cache.isAnimating   = false;
                cache.expanded      = false;
            });

            // show more link
            aux.toggleMore( $openedItem, true );

            $wrapper.find('div.ca-item').each(function(i) {
                var $item   = $(this),
                    idx     = $item.index();

                if( idx !== openedIdx ) {
                    $item.find('div.ca-content-wrapper').css({
                        width   : '0px'
                    })
                    .end()
                    .css( 'left', ( ( cache.winpos - 1 ) - ( openedIdx - idx ) ) * cache.itemW + 'px' )
                    .show();

                    // show more link
                    aux.toggleMore( $item, true );
                }
            });
        },
        // gets the item's position (1, 2, or 3) on the viewport (the visible items)
        // val is the left of the item
        getWinPos   : function( val, cache ) {
            switch( val ) {
                case 0                  : return 1; break;
                case cache.itemW        : return 2; break;
                case cache.itemW * 2    : return 3; break;
            }
        }
    },
    methods = {
        init        : function( options ) {

            if( this.length ) {

                var settings = {
                    sliderSpeed     : 500,          // speed for the sliding animation
                    sliderEasing    : 'easeOutExpo',// easing for the sliding animation
                    itemSpeed       : 500,          // speed for the item animation (open / close)
                    itemEasing      : 'easeOutExpo',// easing for the item animation (open / close)
                    scroll          : 1             // number of items to scroll at a time
                };

                return this.each(function() {

                    // if options exist, lets merge them with our default settings
                    if ( options ) {
                        $.extend( settings, options );
                    }

                    var $el             = $(this),
                        $wrapper        = $el.find('div.ca-wrapper'),
                        $items          = $wrapper.children('div.ca-item'),
                        cache           = {};

                    // save the with of one item    
                    cache.itemW         = $items.width();
                    // save the number of total items
                    cache.totalItems    = $items.length;

                    // add navigation buttons
                    if( cache.totalItems > 3 )  
                        $el.prepend('<div class="ca-nav"><span class="ca-nav-prev">Previous</span><span class="ca-nav-next">Next</span></div>') 

                    // control the scroll value
                    if( settings.scroll < 1 )
                        settings.scroll = 1;
                    else if( settings.scroll > 3 )
                        settings.scroll = 3;    

                    var $navPrev        = $el.find('span.ca-nav-prev'),
                        $navNext        = $el.find('span.ca-nav-next');

                    // hide the items except the first 3
                    $wrapper.css( 'overflow', 'hidden' );

                    // the items will have position absolute 
                    // calculate the left of each item
                    $items.each(function(i) {
                        $(this).css({
                            position    : 'absolute',
                            left        : i * cache.itemW + 'px'
                        });
                    });

                    // click to open the item(s)
                    $el.find('a.ca-more').live('click.contentcarousel', function( event ) {
                        if( cache.isAnimating ) return false;
                        cache.isAnimating   = true;
                        $(this).hide();
                        var $item   = $(this).closest('div.ca-item');
                        aux.openItem( $wrapper, $item, settings, cache );
                        return false;
                    });

                    // click to close the item(s)
                    $el.find('a.ca-close').live('click.contentcarousel', function( event ) {
                        if( cache.isAnimating ) return false;
                        cache.isAnimating   = true;
                        var $item   = $(this).closest('div.ca-item');
                        aux.closeItems( $wrapper, $item, settings, cache );
                        return false;
                    });

                    // navigate left
                    $navPrev.bind('click.contentcarousel', function( event ) {
                        if( cache.isAnimating ) return false;
                        cache.isAnimating   = true;
                        aux.navigate( -1, $el, $wrapper, settings, cache );
                    });

                    // navigate right
                    $navNext.bind('click.contentcarousel', function( event ) {
                        if( cache.isAnimating ) return false;
                        cache.isAnimating   = true;
                        aux.navigate( 1, $el, $wrapper, settings, cache );
                    });

                    // adds events to the mouse
                    $el.bind('mousewheel.contentcarousel', function(e, delta) {
                        if(delta > 0) {
                            if( cache.isAnimating ) return false;
                            cache.isAnimating   = true;
                            aux.navigate( -1, $el, $wrapper, settings, cache );
                        }   
                        else {
                            if( cache.isAnimating ) return false;
                            cache.isAnimating   = true;
                            aux.navigate( 1, $el, $wrapper, settings, cache );
                        }   
                        return false;
                    });

                });
            }
        }
    };

$.fn.contentcarousel = function(method) {
    if ( methods[method] ) {
        return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
        return methods.init.apply( this, arguments );
    } else {
        $.error( 'Method ' +  method + ' does not exist on jQuery.contentcarousel' );
    }
};

})(jQuery); 

有关如何使这项工作的任何想法?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Jquery插件通常如下所示:

(function( $ ) {
  $.fn.myPlugin = function() {
    // Do your awesome plugin stuff here
  };
})( jQuery );

尝试将myPlugin重命名为另一个。可以两个插件使用其他类似插件但不同版本的?您可以找到它们,并重命名其中一个副本,但您需要禁用已更改的WordPress插件的更新