DOCTYPE html>
<html><head><meta charset="utf-8"><title>顶部导航栏效果和返回顶部title>head><body>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body {
background: #ddd;
}
div {
height: 2000px;
}
.nav {
width: 100%;
border-bottom: 1px solid #383e41;
background-color: rgba(0, 0, 0, 0.5);
position: fixed;
top: 0;
height: 80px;
z-index: 11;
}
.nav.active {
background-color: rgba(0, 0, 0, 1);
}
.go-top {
width: 44px;
height: 44px;
background: url(http://images.cnblogs.com/cnblogs_com/lgyong/1411096/t_goTop.png) no-repeat center;
background-size: 100%;
cursor: pointer;
position: fixed;
bottom: 100px;
right: 0;
display: none;
box-shadow: 0 0px 15px 3px rgba(29, 33, 36, 0.3);
}
style>
<div>
<nav class="nav">nav>
<div class="go-top">div>
div>
<script type="text/javascript">
// js
window.onscroll = function () {
console.log('on')
let bannerTopHeight = document.getElementsByClassName('nav')[0];
var t = document.documentElement.scrollTop || document.body.scrollTop;
console.log(t)
console.log(bannerTopHeight.offsetHeight)
if (t >= bannerTopHeight.offsetHeight) {
bannerTopHeight.setAttribute('class', 'nav active')
} else {
bannerTopHeight.setAttribute('class', 'nav')
}
let fixedBox = document.getElementsByClassName('go-top')[0];
if (t >= 300) {
fixedBox.style.display = 'block';
} else {
fixedBox.style.display = 'none';
}
}
script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js">script>
<script type="text/javascript">
// jquery
$(window).scroll(function (event) {
if ($(window).scrollTop() !== 0) {
$(".go-top").fadeIn();
} else {
$(".go-top").fadeOut();
}
$(".go-top").click(function () {
$("html,body").animate({
scrollTop: 0
}, 300);
return false;
})
$(".go-top").on('touchstart',function () {
$("html,body").animate({
scrollTop: 0
}, 300);
return false;
})
var bannerTopHeight = $(".nav").height();
if ($(window).scrollTop() >= bannerTopHeight) {
$(".nav").addClass("active");
} else {
$(".nav").removeClass("active");
}
});
script>
body>html>