要實現該效果,首先要先了解以下幾點基礎知識:
窗體滾動事件:$(window).scroll(function(){...});
獲取窗體滾動距離:$(window).scrollTop();
獲取窗體高度:$(window).height();
了解以上內容就可以實現通過hyperlink控件實現返回頂部的效果了。
1.準備界面結構代碼:
1
<
form
id
="form1"
runat
="server"
>
2
<
div
>
3
<
asp:HyperLink
ID
="Top"
runat
="server"
></
asp:HyperLink
>
4
<
h1
style
="text-align: center"
>
5
利用jQuery實現返回頂部效果
</
h1
>
6
<
div
style
="width: 800px; border: 1px; text-align: left; margin-left: 230px;"
>
7
。。。。。。(很多內容,可以滾動)
8
</
div
>
9
<
asp:HyperLink
ID
="backToTopLink"
runat
="server"
CssClass
="backToTop"
>
回頂部
</
asp:HyperLink
>
10
</
div
>
11
</
form
>
2.給回頂部控件添加樣式:
1
<
style
type
="text/css"
>
2
.backToTop
3
{
4
background-color
:
Yellow
;
5
width
:
30px
;
6
border-style
:
outset
;
7
border-width
:
1px
;
8
text-align
:
center
;
9
font-weight
:
bold
;
10
font-family
:
Arial
;
11
font-size
:
x-large
;
12
cursor
:
pointer
;
13
position
:
absolute
;
// 注意要設置為絕對位置
14
right
:
100px
;
15
}
16
</
style
>
3.添加實現置頂效果腳本代碼:
1
<
script
type
="text/javascript"
>
2
$(document).ready(
function
() {
3
$(
"
#backToTopLink
"
).attr(
"
title
"
,
"
回頂部
"
);
4
$(
"
#backToTopLink
"
).attr(
"
href
"
,
"
#Top
"
); // 通過鏈接實現置頂
5
$(window).scroll(
function
() {
6
if
($(window).scrollTop()
<=
100
) {
7
$(
"
#backToTopLink
"
).fadeOut(
200
);
8
}
9
else
{
10
$(
"
#backToTopLink
"
).fadeIn(
400
);
11
}
12
var
v_Top
=
$(window).height()
-
$(
"
.backToTop
"
).height()
-
10
+
$(window).scrollTop(); // 動態計算滾動后置頂按鈕top位置
13
$(
"
.backToTop
"
).css(
"
top
"
, v_Top
+
"
px
"
);
14
});
15
});
16
</
script
>
注意,本代碼只是為了演示hyperlink控件來實現返回頂部的效果。還可以通過jQuery的動畫效果,實現平滑置頂。
平滑過渡返回頂部代碼如下:
$('#backToTopLink').click(function(){$('html,body').animate({scrollTop: '0px'}, 800);}); // 替換$("#backToTopLink").attr("href", "#Top");即可
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

