commit 23a0cd8 code中文原文

The Perfect "Back to Top" Feature

Author
Yujia Lin
Date
Reading time
2 min read

Translated from Chinese by Claude. Read the original

Mumu already wrote about this a while ago, but I’m going to ramble through it once more anyway. Let’s get straight to the point:

First, load jQuery (if your blog already loads it, don’t load jQuery twice)

1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Then create a JS file named huadong and put the following in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

jQuery(document).ready(function($) {

var s = $('#shangxia').offset().top;

$(window).scroll(function() {
$("#shangxia").animate({
top: $(window).scrollTop() + s + "px"
},
{
queue: false,
duration: 500
})
});
$body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
$('#shang').click(function() {
$body.animate({
scrollTop: '0px'
},
400)
});
$('#xia').click(function() {
$body.animate({
scrollTop: $('#footer').offset().top
},
400)
});
$('#comt').click(function() {
$body.animate({
scrollTop: $('#comments').offset().top
},
400)
});

});

Then load the huadong.js file in the header:

1
<script type="text/javascript" src="http://blueandhack.com/wp-content/themes/white-love/js/huadong.js"></script>

Put the following code in the header:

1
2
3
4
5
6
7
8
9
10

<?php if (is_home()) { ?>

<div id="shangxia"><div id="shang"></div><div id="xia"></div></div>

<?php } else { ?>

<div id="shangxia"><div id="shang"></div><div id="comt"></div><div id="xia"></div></div>

<?php } ?>

CSS code, add it to your theme’s style.css:

1
2
3
4
5
6
7
8

# shangxia{position:absolute;top:40%;left:50%;margin-left:-520px;display:block;}

# shang{background:url(images/huadong.gif) no-repeat;position:relative;cursor:pointer;height:42px;width:32px;margin:10px 0;}

# comt{background:url(images/huadong.gif) no-repeat center -45px;position:relative;cursor:pointer;height:32px;width:32px;margin:10px 0;}

# xia{background:url(images/huadong.gif) no-repeat center -78px;position:relative;cursor:pointer;height:42px;width:32px;margin:10px 0;}

The image you’ll need (remember to put it in the images folder inside your theme)

That’s every step done. The effect is working now, right? Hehe, Mumu’s stuff really is a classic. Original post: “Back to Top” enhanced code, with explanations Why call this the perfect version? Because it’s more complete than Mumu’s: I’ve given you all the materials, so it’s truly foolproof.

Esc

Keyboard shortcuts

Ctrl K /
Search and commands
j k
Next or previous post in a list
Enter
Open the selected post
h l
Older or newer post (on a post)
g h
Go to the log
g a
Go to the archive
g t
Go to tags
g s
Go to stats
t
Switch light or dark theme
r
Random post
?
Show this help