滚动到链接不起作用

时间:2013-12-27 02:51:35

标签: jquery hyperlink scroll jquery-animate

我正在尝试动画我的卷轴,但我正在使用的代码似乎只是跳转到链接而不是动画。我似乎无法找到问题,为什么它不能正常工作。

我在HTML中使用过Jquery - 这可能是个问题吗?我在内部和外部都尝试过。

<doctype html>

<head>
<title>Creative Designer</title>
<link rel="stylesheet" href="css/style.css" type="text/css">


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 2000);
        return false;
      }
    }
  });
});
</script>

</head>


<body>

<nav>
<ul>    
    <li><a href="#home">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#work">Work</a></li>

    </ul>
 </nav>

   <section>
        <h1>featured Projects</h1>

<p id="description">
    I am an Creative Designer Based in Newcastle Upon Tyne
</p>

</section>

<section>


<section id="about">
This is about
</section>



<div id="mainfooter">


</div>

</body>


</html>

1 个答案:

答案 0 :(得分:1)

适合我,使用这个jquery扩展achor滑块和选择器'anchorLink'到你的菜单类:

HTML示例菜单

    <nav>
        <ul>
            <li><a class="introlink anchorLink" href="#intro">Intro</a></li>
            <li><a class="aboutlink anchorLink" href="#about">About</a></li>
            <li><a class="contactlink anchorLink" href="#contact">Contact</a></li>
        </ul>               
    </nav>

HTML部分示例

<section id="intro">

    <h2 class="intro">blah blah blah<span class="sub">blah blah blah</span></h2>

    <p class="featured">blah blah blah</p>


</section>

JQuery锚点滑块:

$(document).ready(function() {
    $("a.anchorLink").anchorAnimate()
});

jQuery.fn.anchorAnimate = function(settings) {

    settings = jQuery.extend({
        speed : 1100
    }, 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;
            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
                window.location.hash = elementClick
            });
            return false;
        })
    })
}