導覽按鈕引導全頁滑動
jQuery 導覽按鈕引導全頁滑動
運用範例練習,了解 jQuery 導覽按鈕引導全頁滑動
準備 HTML & CSS 部份
<body>
<header>
<div id="logo">LOGO</div>
<nav>
<a href="#sec1">Section1</a>
<a href="#sec2">Section2</a>
<a href="#sec3">Section3</a>
<a href="#sec4">Section4</a>
</nav>
</header>
<section id="sec1">Section1</section>
<section id="sec2">Section2</section>
<section id="sec3">Section3</section>
<section id="sec4">Section4</section>
</body>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; }
header { background-color: rgba(0, 0, 0, 0.7); font-weight: bold;
position: fixed; width: 100%; left: 0; top: 0; padding: 20px 50px;
display: flex; justify-content: space-between; align-items: center; }
#logo { color: #f00; font-size: 30px; }
nav a { color: #fff; text-decoration: none; font-size: 20px; padding: 10px; }
nav a:hover { color: #f00; }
section { min-height: 100%; background-color: lightgray; font-size: 50px;
display: flex; justify-content: center; align-items: center; }
section:nth-of-type(even) { background-color: gray; }
</style>
JavaScript & jQuery 部份---導覽按鈕引導全頁滑動
<script>
//滑鼠互動效果#########################################################
//設計下拉式選單第一層按鈕的點選==>滑動整頁到指定的section=====================
$('nav a').click(function(){
//取得點選按鈕的href屬性的內容, 也就是連結的目標
var result = $(this).attr('href');
//偵測對應前往的section的top距離
targetTop = $(result).position().top;
//滑動整頁到指定的位置
$('html,body').animate({scrollTop:targetTop},500);
});
</script>