<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jquery可变透明度返回顶部特效 </title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<style>
body {
font-size: 100%;
color: #f5f4ed;
background-color: #795d6b;
}
a {
color: #e86256;
text-decoration: none;
}
.cd-container {
width: 100%;
height:3000px;
}
.cd-container::after {
content: '';
display: table;
clear: both;
}
header {
background: #5c4751;
height: 100px;
text-align: center;
}
header p {
font-size: 0.8125rem;
color: #957484;
}
main p {
font-size: 1rem;
line-height: 2;
}
.cd-top {
height: 40px;
display: block;
width: 40px;
position: fixed;
bottom: 40px;
right: 10px;
color: #FFFFFF;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
text-align: center;
background: crimson;
overflow: hidden;
white-space: nowrap;
visibility: hidden;
opacity: 0;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.cd-top.cd-is-visible {
/* 按钮变得可见*/
visibility: visible;
opacity: 1;
}
.cd-top.cd-fade-out {
/* 如果用户继续向下滚动,这个按钮的透明度会变得更低 */
opacity: .5;
}
.no-touch .cd-top:hover {
background-color: #e86256;
opacity: 1;
}
#_height{
position: fixed;
text-align: center;
height: 80px;
width: 80px;
bottom: 40px;
left: 10px;
background: #FFFFFF;
color: #000;
}
</style>
</head>
<body>
<header>
<h1>jQuery可变透明度返回顶部代码</h1>
<p>向下拉动滚动条查看效果,超过1200像素,注意按钮的透明度</p>
</header>
<main class="cd-container">
</main>
<a href="#0" class="cd-top">Top</a>
<div id="_height"></div>
</body>
</html>
<script>
jQuery(document).ready(function($){
// 浏览器窗口滚动(像素)后,“回到顶部”链接显示
var offset = 500,
//浏览器窗口滚动(像素)后,“回顶”链接的不透明度降低
offset_opacity = 1200,
//顶部滚动动画的持续时间(在毫秒)
scroll_top_duration = 700,
//“回到顶部”的链接
$back_to_top = $('.cd-top');
//隐藏或显示“回顶”链接
$(window).scroll(function(){
var _height=$(this).scrollTop();
$("#_height").html("当前滚动高度"+_height);
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
//这是三元操作符:当前的滚动条的位置 大于offset吗 ? 如果大于就添加cd-is-visible类名,负责删除cd-is-visible cd-fade-out 类名
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
//平滑滚动到顶部
$back_to_top.on('click', function(event){
event.preventDefault(); //取消默认事件
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
</script>