简体   繁体   中英

move to given div using jquery

In my html i have got div with given class.

After clicking a button I would like to set the position to the top of that div. it may go the in smooth way. How can I do that?

thanks for help

Yep, check this out: http://jsfiddle.net/AlienWebguy/JU3xj/5/

Essentially, we first create a small plugin called scrollTo:

jQuery.fn.extend({
    scrollTo : function(speed, easing) {
        return this.each(function() {
            var targetOffset = $(this).offset().top;
            $('html,body').animate({scrollTop: targetOffset}, speed, easing);
        });
    }
});

Then, getting the html to scroll to that position in the DOM is very simple:

$('div.whatever').scrollTo(300,'linear');

In that code, 300 is the duration - the time it takes for the scroll to happen. The larger the number, the slower it goes. It's in milliseconds, so 1000 would equal 1 second. linear is the easing. For other types of easing, I'd recommend including JQueryUI - have a look at their easing options .

One way is to use the jQuery.ScrollTo plugin , which works similarly to AlienWebguy's suggestion, but with a bunch of extra options you may find useful.

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