Smooth scroll to div id jQuery

2019-01-02 22:03发布

I've been trying to get a scroll to div id jquery code to work correctly. Based on another stack overflow question i tried the following

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

But it didn't work. It just snaps to the div. I also tried

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

With no progress.

11条回答
聊天终结者
2楼-- · 2019-01-02 22:22

You need to animate the html, body

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#myDiv").offset().top
    }, 2000);
});
查看更多
迷人小祖宗
3楼-- · 2019-01-02 22:24

are you sure you are loading the jQuery scrollTo Plugin file?

you might be getting a object: method not found "scrollTo" error in the console.

the scrollTO method is not a native jquery method. to use it you need to include the jquery scroll To plugin file.

ref: http://flesler.blogspot.in/2009/05/jqueryscrollto-142-released.html http://flesler.blogspot.in/2007/10/jqueryscrollto.html

soln: add this in the head section.

<script src="\\path\to\the\jquery.scrollTo.js file"></script>
查看更多
疯言疯语
4楼-- · 2019-01-02 22:24

This is the simplest.Source-https://www.w3schools.com/jsref/met_element_scrollintoview.asp

var elmnt = document.getElementById("content");
elmnt.scrollIntoView();
查看更多
贪生不怕死
5楼-- · 2019-01-02 22:29

You can do it by using the following simple jQuery code.

Tutorial, Demo, and Source code can be found from here - Smooth scroll to div using jQuery

JavaScript:

$(function() {
    $('a[href*=#]:not([href=#])').click(function() {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
        if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    });
});

HTML:

<a href="#section1">Go Section 1</a>
<div id="section1">
    <!-- Content goes here -->
</div>
查看更多
家丑人穷心不美
6楼-- · 2019-01-02 22:34

Here I tried this, that work great for me.

$('a[href*="#"]').on('click', function (e) {
    e.preventDefault();

    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 500, 'linear');
});

HTML:

 <a href="#fast-food" class="active" data-toggle="tab" >FAST FOOD</a>

<div id="fast-food">
<p> Scroll Here... </p>
  </div>
查看更多
Fickle 薄情
7楼-- · 2019-01-02 22:34

This works to me.

<div id="demo">
        <h2>Demo</h2>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $(document).ready(function () {
        // Handler for .ready() called.
        $('html, body').animate({
            scrollTop: $('#demo').offset().top
        }, 'slow');
    });
</script>

Thanks.

查看更多
登录 后发表回答