jQuery Scroller Question
I'm currently trying to implement an up and down button (floating menu) on my portfolio website to scroll a certain amount down the page. For example I would click the down button and it would scroll 100px down and vice versa.
I am currently using this code to scroll to an a specific anchor when a button is clicked but I just want to modify it to shift up or down a set amount of pixels when clicked.
$(document).ready(function(){
$('a[href*=#jump]').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) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop:开发者_如何学运维 targetOffset}, 1000);
return false;
}
}
});
});
The current link in html is : <a class="jump" href="#jump">Back To Top</a>
which scrolls to the anchor : <a id="jump" href="#"></a>
I assume someone would know what I mean straight away but ask me if you need more detail and I can provide an example of what I'm trying to achieve. Help would be appreciated.
You can use jQuery's scrollTop() to adjust the scroll vertical scroll bar.
For instance if your button to scroll down has an id of scrollDownButton
and you want to scroll down the page by 100px then the following code will do that.
$('#scrollDownButton').click( function() {
var currPosition = $('body').scrollTop();
$('body').scrollTop(currPosition + 10);
});
scrollTop()
will give you the current position of the vertical scroll bar and scrollTop(value)
will set it to the given position.
If you want to scroll up the page then subtract from the current value rather than add.
Note: You want to select whichever element has the scroll bar. In the above example it was the <body>
, but <html>
is also a common element. Also scrollTop() was implemented in JQuery 1.2.6 make sure your version is new enough.
Update: How to animate the scroll.
If you want to animate the scroll and see it happen rather than just jump down or up you can use the following code:
$('#scrollDownButton').click( function() {
var currPosition = $('body').scrollTop();
$('body').animate({scrollTop: currPosition+100}, 'slow');
})
Update for Ryan
Here is the code for your specific page.
$('document').ready( function() {
$('#scrollDownButton').click( function() {
var currPosition = $('html').scrollTop();
$('html').animate({scrollTop: currPosition+100}, 'slow');
});
});
One approach could be to use jQuery's ScrollTo and simply specify an offset amount.
jQuery ScrollTo
For example, you could have it always scroll to the same element, but change the offset value by increments of 100px, ect.
But I'd imagine there is a much better way than this out there...
精彩评论