给网站添加一个侧边导航栏功能
时间:2023-7-25 20:53 作者:小诸葛 分类: 前端 正在检查是否收录...
给网站添加一个侧边导航栏功能可以添加一些快捷的功能:如果网站管理员联系方式、一键前往底部、一键返回顶部...
如图:
代码如下:
HTML
<div class="toTop">
<ul>
<li id="bottom"><img src="https://www.v6g.cn/content/templates/VG/images/bottom.png"></li>
<li> <img src="https://www.v6g.cn/content/templates/VG/images/qq.png"></li>
<li><img src="https://www.v6g.cn/content/templates/VG/images/wx.png"></li>
<li id="top"><img src="https://www.v6g.cn/content/templates/VG/images/top.png"></li>
</ul>
</div>
Css
/*首页菜单*/
.toTop {
position: fixed;
right: 0;
bottom: 0;
color: #000;
padding: 10px;
cursor: pointer;
border-radius: 11px;
-webkit-tap-highlight-color:transparent;
}
.toTop ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.toTop li{
width: 35px;
height: 35px;
margin: 5px 0;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ffffff85;
position: relative;
overflow: hidden;
}
.toTop li img{
width: 60%;
height: 60%;
}
.toTop li::after{
content: "";
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: #fff;
z-index: -1;
filter: blur(5px);
}
JavaScript
const toTop = document.querySelector('#top');
const bottom = document.querySelector('#bottom');
const scrollStep = 20;
toTop.addEventListener('click', scrollToTop);
bottom.addEventListener('click', scrollToBottom);
window.addEventListener('scroll', handleScroll);
document.addEventListener('DOMContentLoaded', handleScroll); // 在页面加载完成时执行一次
function scrollToTop() {
let y = window.scrollY;
const timer = setInterval(function() {
y -= scrollStep;
window.scrollTo(0, y);
if (y <= 0) {
clearInterval(timer);
}
});
}
function scrollToBottom() {
let y = window.scrollY;
const scrollHeight = document.documentElement.scrollHeight;
const windowHeight = window.innerHeight;
const timer = setInterval(function() {
y += scrollStep;
window.scrollTo(0, y);
if (y >= scrollHeight - windowHeight) {
clearInterval(timer);
}
});
}
function handleScroll() {
const scrollThreshold = 200;
const isScrolledPastThreshold = window.scrollY >= scrollThreshold;
toTop.style.display = isScrolledPastThreshold ? 'flex' : 'none';
bottom.style.display = isScrolledPastThreshold ? 'none' : 'flex';
}
推荐阅读:
扫描二维码,在手机上阅读