I searched this site but all I found is jQuery scrolling to top. How can I scroll to certain link or bookmark in bottom?

e.g. if I click a button: <a href="page.php?#contact_us">Contact Us</a> then it should scroll the page down to bookmark: <a name="contact_us"></a> with jQuery. How can I go about this?

有帮助吗?

解决方案

You can try this code too:

function scrollToAnchor(aid){
   var aTag = $("a[name='"+ aid +"']");
   $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

$(".link").on('click', function() {
   scrollToAnchor(this.id);
});

Fiddle in action

Here .link is the class name of your anchor tag and id1, id2, id3..and so on is the id for each anchor, and you have to bind an click event on anchor link and pass the id in the function named scrollToAnchor(aid){...} where aid is the param for id which is passed from the bound event.

其他提示

Try jQuery animateScroll (http://plugins.compzets.com/animatescroll/), this plugin will add you smoth css3 effect.

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="animatescroll.js">
    </head>
    <body>
        <div id="section-1">This is the element where you want to scroll to<div>

        // You may call the function like this
        <a onclick="$('[id-or-class-of-element]').animatescroll();">Go to Element</a>
    </body>
</html>

how about this

Fiddle Link

<script type="text/javascript">
$( document ).ready(function() {

    function scrollToByName(element) {
        // read target name, remove hash-tag
        var aTargetName = element.attr('href').split("#");
        var sTargetName = aTargetName[aTargetName.length-1];
        var jqTarget = $("a[name=" + sTargetName + "]");
        var sSpeed = "slow";

        // check if element exists
        if (jqTarget.length > 0) {
            // animate view to the target
            $('html,body').animate({scrollTop: jqTarget.offset().top}, sSpeed);
        }
    }

    $('.scroll-trigger').on('click', function (event) {
        // prevent default 'jump'
        event.preventDefault();
        scrollToByName($(this));
        return false;
    });
});
</script>

with html

the trigger

<a href="page.php?#contact_us" class="scroll-trigger">Take me there.</a>

and the target

<a name="contact_us" href="#">Contact us</a>

Hope it works for you.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top