我是jquery的新手,我正在尝试使用由Cedric Dugas为我的网站编写的jquery锚码。它运行良好,但如果我有一个不使用#的自定义链接,那么该链接将不会重定向到任何地方。
所以,据我所知,event.preventDefault()阻止谷歌链接被打开,我不知道如何覆盖这个。请帮我!谢谢。
/*******
*** Anchor Slider by Cedric Dugas ***
*** Http://www.position-absolute.com ***
Never have an anchor jumping your content, slide it.
Don't forget to put an id to your anchor !
You can use and modify this script for any project you want, but please leave this comment as credit.
~ MODIFIED! ~
*****/
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 500,
offset : 0
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault();
var locationHref = window.location.href;
var elementClick = $(caller).attr("href");
var destination = $(elementClick).offset().top - settings.offset;
if (destination < 0) {
destination = 0;
}
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
});
return false;
})
})
}
<div>
<ul>
<li>
<a href="#link1"> Homepage </a>
</li>
</ul>
<ul>
<li>
<a href="#link2"> Product </a>
</li>
</ul>
<ul>
<li>
<a href="#link3"> About us </a>
</li>
</ul>
</div>
<div>
<ul>
<li>
<a href="https://www.google.com"> Google link </a>
</li>
</ul>
</div>
答案 0 :(得分:0)
基本上你需要检查链接是否有。
你可以通过多种方式做到这一点,我将发布一种最简单的方法。
您只需在此代码if($(caller).attr("href").charAt(0) == "#"){}
中包围代码块即可。它只是检查href中的第一个字符是否为#,如果是,则继续执行其他操作。
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 500,
offset : 0
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
if($(caller).attr("href").charAt(0) == "#"){
event.preventDefault();
var locationHref = window.location.href;
var elementClick = $(caller).attr("href");
var destination = $(elementClick).offset().top - settings.offset;
if (destination < 0) {
destination = 0;
}
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
});
return false;
}
})
})