實作效果
在網站頁面上,點選某個超連結,頁面跳轉到某個位置,跳轉過程有一個動畫滾動效果,這是一種比較酷的體驗。這種效果是如何實作的呢,本文通過實際代碼來詳解實作方法。
實作代碼
網頁代碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>滾屏效果</title>
<script src="./assets/js/jquery.min.js"></script>
</head>
<body style=" margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; ">
<div id="header" style="height: 100px;">
<a id="tech" class="scroll-a" href="#hi-tech">技術</a>
<a id="code" class="scroll-a" href="#hi-code">代碼</a>
</div>
<div style="background-color: gray;height: 600px;">
<h1>間隔</h1>
</div>
<div style="background-color: white;height: 600px;" id="hi-tech">
<h1>技術</h1>
<a id="tohead1" class="scroll-a" href="#header">傳回頂部</a>
</div>
<div style="background-color: gray;height: 600px;" id="hi-code">
<h1>代碼</h1>
<a id="tohead" class="scroll-a" href="#header">傳回頂部</a>
</div>
</body>
<script>
$('#tech').on("click", function () {
$('html,body').animate({scrollTop:$('#hi-tech').offset().top}, 800);
return false;
});
$('#code').on("click", function () {
$('html,body').animate({scrollTop:$('#hi-code').offset().top}, 800);
return false;
});
$('#tohead').on("click", function () {
$('html,body').animate({scrollTop:$('#header').offset().top}, 800);
return false;
});
$('#tohead1').on("click", function () {
$('html,body').animate({scrollTop:$('#header').offset().top}, 800);
return false;
});
</script>
</html>
這裡主要用到了jquery的animate方法,實作思路是,當點選某個超連結時,通過jquery的animate将螢幕滾動到某個位置。注意animate函數的兩個參數,一個是滾動位置,一個是動畫滾動的時間毫秒。
$('#tech').on("click", function () {
$('html,body').animate({scrollTop:$('#hi-tech').offset().top}, 800);
return false;
});
雖然實作了效果,這裡有個問題,如果滾動的超連結較多,那麼就要寫不少重複代碼,還要注意滾動位置不要寫錯。下面通過改變一下jquery選擇器來優化代碼。
優化代碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>滾屏效果</title>
<script src="./assets/js/jquery.min.js"></script>
</head>
<body style=" margin-left: 0px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; ">
<div id="header" style="height: 100px;">
<a id="tech" class="scroll-a" href="#hi-tech">技術</a>
<a id="code" class="scroll-a" href="#hi-code">代碼</a>
</div>
<div style="background-color: gray;height: 600px;">
<h1>間隔</h1>
</div>
<div style="background-color: white;height: 600px;" id="hi-tech">
<h1>技術</h1>
<a id="tohead1" class="scroll-a" href="#header">傳回頂部</a>
</div>
<div style="background-color: gray;height: 600px;" id="hi-code">
<h1>代碼</h1>
<a id="tohead" class="scroll-a" href="#header">傳回頂部</a>
</div>
</body>
<script>
$('.scroll-a').on("click", function () {
let scrollto = $(this).attr('href');
$('html,body').animate({scrollTop:$(scrollto).offset().top}, 800);
return false;
});
</script>
</html>