实现效果

在网站页面上,点击某个超链接,页面跳转到某个位置,跳转过程有一个动画滚动效果,这是一种比较酷的体验。这种效果是如何实现的呢,本文通过实际代码来详解实现方法。

实现代码

网页代码

<!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>

可以看出,通过使用jquery class选择器,并使用jquery的this对象获取滚动目标,明显减少了代码,代码看起来更加清楚。