简体   繁体   中英

JavaScript 'smooth scroll' will not scroll

Question background:

I'm developing a single page site using Twitter Bootstrap 3 within an ASP.NET MVC project.

The problem:

Im currently attempting to implement 'smooth scrolling' that should scroll to to the relevant div with clicked from the navbar drop down. At the moment when a section is clicked from the navbar drop down it 'jumps' to the div rather than scroll.

The code:

This following is my '_Layout.cshtml' markup with provides the navbar and footer. The JavaScript for the scroll is shown between the script tags:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
    <script>
        $('#nav .navbar-nav li>a').click(function () {
            var link = $(this).attr('href');
            var offSet = 30;
            var targetOffset = $(link).offset().top - offSet;
            $('html,body').animate({ scrollTop: targetOffset }, 7000);
        });
</script>
</head>
<body>
<div class="navbar navbar-fixed-top">

    <nav class="navbar navbar-default" role="navigation" id="nav">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/"><img src="images/logo.png" alt="yourLogo"></a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">Link</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#myCarousel">Projects</a></li>
                            <li><a href="#Welcome">Welcome</a></li>
                            <li><a href="#features">Thing</a></li>
                            <li><a href="#About">About Me</a></li>
                            <li><a href="#Location">Location</a></li>
                            <li><a href="#Contact">Contact Me</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
</div>

<div class="container body-content">
    @RenderBody()
</div>

<footer>
    <!-- This HTML is outside the other container above i.e its separate. You need a container as this allows you to use bootstrap classes -->
    <div class="container">
        <div class="row">
            <div class="col-sm-2">
                <h6>Copyright &copy; 2014</h6>
            </div>

            <div class="col-sm-4">
                <h6>About Us</h6>
                <p>Chia dreamcatcher artisan vinyl Intelligentsia Banksy. Art party whatever cred wolf hella distillery Portland wayfarers Kickstarter, kale chips pug artisan +1 crucifix.</p>
            </div>

            <div class="col-sm-2">
                <h6>Navigation</h6>
                <ul class="unstyled">
                    <li><a href="#">Home</a></li>
                    <li><a href="#">Services</a></li>
                    <li><a href="#">Links</a></li>
                    <li><a href="#">Contact</a></li>
                </ul>
            </div>

            <div class="col-sm-2">
                <h6>Follow Us</h6>
                <ul class="unstyled">
                    <li><a href="#">Twitter</a></li>
                    <li><a href="#">Facebook</a></li>
                    <li><a href="#">Google Plus</a></li>
                </ul>
            </div><!-- end col-sm-2 -->

            <div class="col-sm-2">
                <h6>Coded with<span class="glyphicon glyphicon-heart"> by Me</span></h6>


            </div>
        </div>
    </div>
</footer>
</body>


@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

Screenshots:

The following screenshots shown that when the navbar option are clicked the page go to the correct div, but it will not scroll. Any help resolving this would be great.

在此处输入图片说明

After a bit more research and using this great example: http://alijafarian.com/responsive-page-scrolling-with-jquery-and-bootstrap/ I managed to produce the solution below which works perfectly.

 <script>

    $(document).ready(function() {
        $('#nav .navbar-nav li>a').on('click', function(event){
            event.preventDefault();
            var sectionID = $(this).attr("href");
            scrollToID(sectionID, 750);
        });

        function scrollToID(id, speed)
        {
            var offSet = 70;
            var targetOffset = $(id).offset().top - offSet;
            $('html,body').animate({scrollTop:targetOffset}, speed);
        }
        });
 </script>

Try adding "px" to scrolltop :

$('#nav .navbar-nav li>a').click(function () {
        var link = $(this).attr('href');
        var offSet = 30;
        var targetOffset = $(link).offset().top - offSet;
        $('html,body').animate({ scrollTop: targetOffset + "px" }, 7000);
    });

or this :

$('#nav .navbar-nav li>a').click(function () {
        var link = $(this).attr('href');
        var offSet = 30;
        var targetOffset = $(link).offset().top - offSet;
        $('html,body').animate({ scrollTop: targetOffset }, 'slow');
    });

i think you need to execute it after the page is loaded :

$(document).ready(function () {
    $('#nav .navbar-nav li>a').click(function () {
        var link = $(this).attr('href');
        var offSet = 30;
        var targetOffset = $(link).offset().top - offSet;
        $('html,body').animate({ scrollTop: targetOffset }, 'slow');
    });
});
    <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
        }, 1000);
        return false;
      }
    }
  });
});
</script>

Taken from: [ http://css-tricks.com/snippets/jquery/smooth-scrolling/]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM