嘿那里:)我有脚本,当你点击锚点时添加fadeIn和fadeOut效果。
但它针对我的所有锚点。是否存在空白以避免从特定链接执行,例如我的"返回顶部"链接在页脚中。它会为该链接添加效果,并且不会停止,因为没有目标网址。
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>
答案 0 :(得分: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"');
});
&#13;
<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>
&#13;
答案 1 :(得分: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;
});
答案 2 :(得分:0)
另一种方法是仅在要执行的链接上添加CSS类。
$(document).on("click", "a.do-action", ...
它还可以更容易地查看哪些链接可以操作。
如果不应单击链接,则可能需要使用其他标记。