1

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

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

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

ajaxify-html5 脚本已经能够阻止与某个类的链接。如果我可以利用该功能并将其一分为二,我将准备就绪(即,我会将类 .go-to-divA 用于某些链接,将 .go-to-divB 用于其他链接)。

4

2 回答 2

1

我一直在寻找解决方案,我想我们必须首先考虑一些事情才能使其发挥作用。

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

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

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

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

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

于 2013-09-18T06:24:16.097 回答
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
于 2013-09-20T04:45:03.347 回答