修改balupton ajaxify-html5.js使用两个不同的区域(div)

时间:2013-01-08 15:09:36

标签: jquery history.js ajaxify

ajaxify-html5.js by balupton:https://github.com/browserstate/ajaxify

我需要修改这个很棒的脚本来实现以下场景:

我页面上的某些链接需要将内容加载到一个div中,然后滚动到它,我页面上的其他链接需要将内容加载到另一个div中,然后滚动到它。

ajaxify-html5脚本已经能够阻止某个类的链接。如果我能够利用这个功能并将其分成两部分,那么我将全力以赴(即。我会将类.go-to-divA用于某些链接而.go-to-divB用于其他链接)。

2 个答案:

答案 0 :(得分:1)

我正在寻找一个解决方案,我想我们必须先考虑一些事情才能让它发挥作用。

1 - 我们必须制作2个不同的div容器来加载内容。让我们命名第一个“主容器”和第二个“子容器”。

2 - 我们需要两个不同的链接类来指向您已经放置的不同div容器。 '.go-to-divA'和'.go-to-divB'。

3 - Ajaxify-html5.js正在将url更改为单击的ahref链接。

这两个类都会更改网址,但功能会有所不同。例如,'。go-to-divA'将加载一个页面,其中“main-container”也包含“子容器”并淡入整个内容。现在“main-container”中的类与“.go-to-divB”的链接将加载“子容器”中淡入和淡出div的内容。

所以我想对于这个解决方案,页面的结构在我们利用脚本功能的方式上起着重要作用。我们必须对此进行测试,看看它是如何进行的

答案 1 :(得分:1)

以下是我最终如何做到这一点。你可以忽略一些额外的东西。

// History.js It!
// v1.0.1 - 30 September, 2012
// https://gist.github.com/854622
(function(window,undefined){

  // Prepare our Variables
  var
    History = window.History,
    $ = window.jQuery,
    document = window.document;

  // Check to see if History.js is enabled for our Browser
  if ( !History.enabled ) {
    return false;
  }

  if ($.browser.msie && parseInt($.browser.version, 10) > 9) {
    return false;
  }

  // Wait for Document
  $(function(){

    // Prepare Variables
    var
    /* Application Specific Variables */
    contentSelector = '#contenucoeur',
    replaceZoneActus = '.emplacementactu',
    scrollZoneActus = '#topemplacementactu',
    replaceZoneArticles = '.emplacementarticle',
    scrollZoneArticles = '#topemplacementarticle',
    $contentActus = $(replaceZoneActus),
    $contentArticles = $(replaceZoneArticles),
    contentNodeActus = $contentActus.get(0),
    contentNodeArticles = $contentArticles.get(0),
    $blocArticle = $('.blocArticle'),
    $menu = $('.articualites'),
    activeClass = 'articleactive',
    activeSelector = '.articleaactive',
    menuChildrenSelector = '> article',
    completedEventName = 'statechangecomplete',
    /* Application Generic Variables */
    $window = $(window),
    $body = $(document.body),
    testurl = History.getHash(),
    rootUrl = History.getRootUrl();

    console.log( History, testurl );

    // Ensure Content
    if ( $contentActus.length === 0 || $contentArticles.length === 0 ) {
      $content = $body;
    }

    // Internal Helper
    $.expr[':'].internal = function(obj, index, meta, stack){
      // Prepare
      var
        $this = $(obj),
        url = $this.attr('href')||'',
        isInternalLink;

      // Check link
      isInternalLink = url.substring(0,rootUrl.length) === rootUrl || url.indexOf(':') === -1;

      // Ignore or Keep
      return isInternalLink;
    };

    // HTML Helper
    var documentHtml = function(html){
      // Prepare
      var result = String(html)
        .replace(/<\!DOCTYPE[^>]*>/i, '')
        .replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
        .replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>');

      // Return
      return result;
    };

    // Ajaxify Helper
    $.fn.ajaxify = function(){

      // Prepare
      var $this = $(this);

      // Ajaxify
      $this.find('#columns a:not(.btPrint, .linkMore, .linkScroll, .backtopPag, .linkRssActu a, .fluxrsspresse a, .wrapFiltreFAQ a, .page-sitemap .inside a, .titleSearchResult a, .itemWaypoint, .profilLink a, .field-liens-internes a, #ctaDiscover, .downloadMedia a, .homeLink, .wrapFormulaire a, .noAjax, .wrapperArticle a, a[href$=".pdf"], a[href|="http"], a[rel="external"], .wrapError a, .popin a )').live('click', function(event){

        event.preventDefault();

        // Prepare
        var $this = $(this),
            url = $this.attr('href'),
            title = $this.attr('title')||null;

        // variable de la pagination =< cas des précédent - suivant
        pagin = $this.hasClass('linkPag');
        // variable d'empalcement cible de chargement
        emplacement = $this.attr('data-emplacement');

        if( $this.is('.accordilink, .sliderlink, .lienFamille, .closeArticle') ) {

          var idSlider = parseInt( $this.attr('data-slider'), 10 ),
              idAccordeon = parseInt( $this.attr('data-accordeon'), 10 ),
              idBrand = $this.attr('data-category');

          if( $this.is('.closeArticle') ){

            $this.parents('.block-content').fadeOut(700, function(){
              $this.empty();
            });

            if( /homeactus|intranav_homeactus/.test(emplacement) ) {

              if( $('html').attr('lang') == 'fr' ) {
                url = '/';
              } else {
                url = '/en';
              }

              title = 'kendrick ';

              setTimeout(function(){jQuery.scrollTo('#mini-panel-blue_bar', 800, {'axis':'y'});}, 300);

              $blocArticle.removeClass('active');

            } else
            if( /articles|intranav_articles|intranav_brands/.test(emplacement) ) {

              setTimeout(function(){jQuery.scrollTo('.titlePage', 800, {'axis':'y'});}, 300);

              $blocArticle.removeClass('active');

            } else
            if( /actualites|intranav_actualites/.test(emplacement) ) {

              setTimeout(function(){jQuery.scrollTo('.panelsRegion-kendrick_basic-actualit__s-inside', 800, {'axis':'y'});}, 300);

              $blocArticle.removeClass('active');

            }

          } else if( $this.is('.accordilink') ){

            jQuery('.view-rubrique-slider .view-content').accordion('activate', jQuery('#' + idAccordeon + 'rubriqueaccordion').prevAll().length);

            setTimeout(function(){jQuery.scrollTo('#' + idAccordeon + 'rubriqueaccordion', 800, {'axis':'y'});}, 300);

          } else if( $this.is('.lienFamille') ){

            jQuery('.view-marque-accordion .view-content').accordion('activate', jQuery('#' + idBrand).prevAll().length );

            setTimeout(function(){jQuery.scrollTo('#' + idBrand, 800, {'axis':'y'});}, 300);

          } else if( $this.is('.sliderlink') ){

            if ($('#views_slideshow_cycle_main_rubrique_slider-mainslider').length) {

              $('#views_slideshow_pager_field_item_bottom_rubrique_slider-mainslider_' + idSlider + '').trigger('click');
              //Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": 'rubrique_slider-mainslider', "slideNum": idSlider });

            }

          }

        } else {

          /* état actif */
          if (!pagin) {

            $('.blocArticle', $('.view-articles')).removeClass('active');
            $this.parents('figure').addClass('active');

          } else {

             dirNext = $this.hasClass('nextActu');

          }

        }

        History.pushState(null,title,url);

        // Continue as normal for cmd clicks etc
        if ( event.which == 2 || event.metaKey ) { return true; }

        // Ajaxify this link
        return false;

      });

      // Chain
      return $this;
    };

    // Ajaxify our Internal Links
    $body.ajaxify();

    // Hook into State Changes
    $window.bind('statechange',function(){
      // Prepare Variables
      var
        State = History.getState(),
        url = State.url,
        url_split = State.url.split('/'),
        relativeUrl = url.replace(rootUrl,'');

        if( url_split.length > 4 ){
          var urlPop = url_split.pop()[0].substring(0, 1);
        }

      // Ajax Request the Traditional Page
      $.ajax({
        beforeSend: function() {

          // Start Fade Out
          // Animating to opacity to 0 still keeps the element's height intact
          // Which prevents that annoying pop bang issue when loading in new content
          // Call emplacement specific actions
          // and only if new content was request
          if( urlPop == '_' ){
            // optimisation http://www.onextrapixel.com/2013/02/21/improve-your-code-with-smart-javascript-techniques-and-patterns/
            if( /articles|intranav_articles|intranav_brands/.test(emplacement) ) {

              //On crée juste la div pour le loader
              $('<div />', {'id':'loader', 'height':'24px'}).prependTo(scrollZoneArticles);

              $contentArticles.animate({
                opacity: 0
              }, 800);

              $.scrollTo(scrollZoneArticles, 800, {'axis':'y'});

            } else if( /actualites|homeactus|intranav_actualites|intranav_homeactus/.test(emplacement) ) {

              //On crée juste la div pour le loader
              $('<div />', {'id':'loader', 'height':'24px'}).prependTo(scrollZoneActus);

              $contentActus.animate({
                opacity: 0
              }, 800);

              $.scrollTo(scrollZoneActus, 800, {'axis':'y'});
            }

          } else {

            $('#topemplacementactu, #topemplacementarticle').find('.view-content').empty();

            $blocArticle.removeClass('active');

            return false;

          }

        },
        url: url,
        success: function(data, textStatus, jqXHR){

          // Prepare
          var
            $data = $(documentHtml(data)),
            $dataTitle = $data.find('.document-title'),
            $dataBody = $data.find('.document-body:first'),
            $dataContent = $dataBody.find(contentSelector).filter(':first'),
            $menuChildren,
            contentHtml = $dataContent.html()||$data.html(),
            $scripts;

          // Fetch the scripts
          $scripts = $dataContent.find('.document-script');
          if ( $scripts.length ) {
            $scripts.detach();
          }

          // Fetch the content
          // contentHtml = $dataContent.html()||$data.html();

          // if contentHtml is null-vide
          if ( !contentHtml ) {
            //document.location.href = url;
            return false;
          }
          function animateLoad(el, elScroll) {

            if (!pagin) {

                el.html(contentHtml).css('opacity', 100);

            } else {

                // if (dirNext) {
                //     var marginLeft = $VAR.widthWindow;
                // } else {
                //     var marginLeft = -$VAR.widthWindow;
                // }

                var marginLeft = -$VAR.widthWindow;


                el.html(contentHtml).css({
                    'opacity': 100,
                    'margin-left': marginLeft,
                    'width': ($VAR.widthWindow > 1280) ? '1280' : $VAR.widthWindow
                }).animate({
                    'margin-left': 0
                }, 500, function(){

                    $(this).css('width', 'auto');

                });

            }

            el.find('.closeArticle').attr('data-emplacement', emplacement).attr('data-accordeon');

            $.scrollTo(elScroll, 800, {'axis':'y'});

          }

          // Update the content if needed

          if( /articles|intranav_articles|intranav_brands/.test(emplacement) ) {

            animateLoad($contentArticles, scrollZoneArticles);

          } else
          if( /actualites|homeactus|intranav_actualites|intranav_homeactus/.test(emplacement) ) {

            animateLoad($contentActus, scrollZoneActus);

          }

          if( $('.innerDiapo').length ){

            setTimeout(initDiapo, 1000);

          }

          if( $('#map').length ){

            setTimeout(imageMap, 1000);

          }

          // Update the title
          document.title = $dataTitle.text();
          try {
            document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
          }
          catch ( Exception ) { }

          // Add the scripts
          $scripts.each(function(){
            var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
            scriptNode.appendChild(document.createTextNode(scriptText));
            contentNode.appendChild(scriptNode);
          });

          // We clear out the loader zone
          $('#loader').remove();
          $window.trigger(completedEventName);

          // Inform Google Analytics of the change
          if ( typeof window._gaq !== 'undefined' ) {
            window._gaq.push(['_trackPageview', relativeUrl]);
          }

          // Inform ReInvigorate of a state change
          if ( typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined' ) {
            reinvigorate.ajax_track(url);
            // ^ we use the full url here as that is what reinvigorate supports
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
          document.location.href = url;
          return false;
        }
      }); // end ajax

    }); // end onStateChange

  }); // end onDomLoad

})(window); // end closure