2015-05-26 51 views
1

嘿那裏:)我有添加淡入淡出和淡出效果,當你點擊錨點的腳本。停止特定鏈接上的JavaScript執行

但它瞄準我所有的錨點。是否有一個空白,以避免從特定鏈接執行,如我的「返回頁首」鏈接在頁腳。它爲該鏈接添加效果,並且不會停止,因爲沒有目標網址。

JS:

// Page transitions and preventing FOUC(flash of unstyled content). 
jQuery.holdReady(true); 
jQuery("body").css("opacity", 0); 
jQuery.holdReady(false); 
jQuery(function ($) { 
    $("body").fadeTo(1500, 1); 
    $(document).on("click", "a", function (event) { 

     // get the href attribute 
     // "this" is still the <a> element here 
     var newUrl = $(this).attr("href"); 

     event.preventDefault(); 
     $("body").fadeTo(800, 0, function() { 

      //here, where you were trying to get the url, "this" 
      //points to the animated element, ie body 


      // veryfy if the new url exists or is a hash 
      if (!newUrl || newUrl[0] === "#") { 
       // set that hash 
       location.hash = newUrl; 
       return; 
      } 

      //just update the location without fading in at this point 
      location = newUrl; 

      // prevent the default browser behavior. 
      return false; 
     }); 
    }); 
}); 

和鏈接到頁面頂部看起來是這樣的:

  <a class="to-top" href="#masthead"> 
       <svg class="skull-up"> 
        <use xlink:href="#skull"></use> 
       </svg> 
       <span class="screen-reader-text">Tilbage til top</span> 
      </a> 

回答

2

使用event.stopPropagation();

$(document).on("click", "a", function (event) { 
 
    alert('Clicked on a'); 
 
    return false; 
 
}); 
 
$('.to-top').on('click', function(event){ 
 
    event.stopPropagation(); 
 
    alert('Clicked on a with class "to-top"'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a href="#something">I am a tag</a> 
 

 
<a class="to-top" href="#something">I am a tag to top</a>

+0

耶,就像一個魅力:)今天學到了一些新的史詩!謝謝。 –

0

你應該將返回FALSE;到click事件的回調函數......現在你調用return false;當動畫完成時,它並沒有做任何事情!

$(document).on("click", "a", function (event) { 

    // get the href attribute 
    // "this" is still the <a> element here 
    var newUrl = $(this).attr("href"); 

    event.preventDefault(); 
    $("body").fadeTo(800, 0, function() { 

     //here, where you were trying to get the url, "this" 
     //points to the animated element, ie body 


     // veryfy if the new url exists or is a hash 
     if (!newUrl || newUrl[0] === "#") { 
      // set that hash 
      location.hash = newUrl; 
      return; 
     } 

     //just update the location without fading in at this point 
     location = newUrl; 

    }); 
    // prevent the default browser behavior. 
    return false; 
}); 
0

另一種方法是隻在要執行的鏈接上添加CSS類。

$(document).on("click", "a.do-action", ... 

這也可以更容易地看到哪些鏈接是可操作的。

如果鏈接不應被點擊,您可能需要使用不同的標籤。