If you noticed I have a ‘Back to top’ link appearing at the bottom right everytime you scroll down the page. Wonder how it was made? I’ll tell you. It’s quite simple. What you need is a div containing the text, apply some css and add an event using jQuery.

First, create the div:

<div id="toTop">^ Back to Top</div>

Then add style to it, add this in your css file or inside <style> tag:

#toTop {
	width:100px;
        border:1px solid #ccc;
        background:#f7f7f7;
        text-align:center;
        padding:5px;
        position:fixed; /* this is the magic */
        bottom:10px; /* together with this to put the div at the bottom*/
        right:10px;
        cursor:pointer;
        display:none;
        color:#333;
        font-family:verdana;
        font-size:11px;
}

And last, the jQuery code:

<script src="path/to/js/jquery.js"></script>
<script type="text/javascript">
$(function() {
	$(window).scroll(function() {
		if($(this).scrollTop() != 0) {
			$('#toTop').fadeIn();	
		} else {
			$('#toTop').fadeOut();
		}
	});
 
	$('#toTop').click(function() {
		$('body,html').animate({scrollTop:0},800);
	});	
});
</script>

There you have it! Simple isn’t it? :)
This works in Firefox 3.0.10 – 3.6.13, Internet Explorer 7 (Strict Mode) and 8, Google Chrome, jQuery 1.4.3.

Remember: On IE 7, your page needs to be at strict mode, just add a doctype at the top of your page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Hope that helps :)

Sorry no IE 6 support and also I think it doesn’t work in Quirks Mode (will see if it’s possible) :(

Let me know if something is missing in the code sample, for some reason it always gets deleted every time I update the post in the visual editor.

Check a working sample here.

Comments closed due to spamming. If you have questions, please send me an email which can be found here.

原文取自:http://agyuku.net/2009/05/back-to-top-link-using-jquery/

參考來源:http://webdesignandsuch.com/10-jquery-back-to-top-link-solutions-for-websites/


arrow
arrow
    文章標籤
    JQuery 返回頂端 Top
    全站熱搜

    Frank 發表在 痞客邦 留言(0) 人氣()