實現側邊欄,點擊菜單按鈕側邊欄顯示,點擊遮罩區域側邊欄收起。
實現返回頂部,回到頂部按鈕在第二屏才會出現,回到第一屏消失。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SideBar</title>
</head>
<script src="jquery-3.1.1.min.js"></script>//jQuery,請自行前往官網下載
<script>
$(function(){
var sidebar = $('#sidebar');
var mask = $('.mask');
var btnsidebar = $('#btnsidebar');
var btntop = $('#btntop');
btnsidebar.on('click',function(){//監聽菜單按鈕
mask.fadeIn();
sidebar.css('right',0);
});
mask.on('click',function(){//監聽遮罩區域點擊事件
mask.fadeOut();
sidebar.css('right',-sidebar.width());
});
btntop.on('click',function(){//監聽返回頂部按鈕
$('html,body').animate({
scrollTop:0
},800)
})
$(window).on('scroll',function(){//監聽滾動事件
if($(window).scrollTop()>$(window).height()){
btntop.fadeIn();
}else{
btntop.fadeOut();
}
});
$(window).trigger('scroll');//加載頁面后觸發滾動事件
});
</script>
<style>
.mask//遮罩區域
{
display: none;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: rgba(0,0,0,0.3);
}
#sidebar/*側邊欄*/
{
position:fixed;
width: 300px;
background: #333;
top: 0;
bottom: 0;
right: -300px;
transition: 0.5s;
}
#sidebar ul
{
list-style: none;
padding: 0;
margin: 0;
}
#sidebar ul a/*側邊欄菜單*/
{
text-decoration: none;
padding:20px 50px;
display:inline-block;
color: #fff;
width: 100%;
}
#sidebar ul a:hover/*側邊欄菜單鼠標懸停*/
{
background: #444;
}
body
{
height: 3000px;
}
#btntop/*返回頂部按鈕*/
{
position: fixed;
bottom: 30px;
right: 30px;
}
#btnsidebar/*側邊欄按鈕*/
{
position: fixed;
top: 30px;
right: 30px;
}
</style>
<body>
<a href="javascript:;" id="btnsidebar">菜單</a>
<a href="javascript:;" id="btntop">返回頂部</a>
<div class="mask"></div>
<div id="sidebar">
<ul>
<li><a href="">item1</a></li>
<li><a href="">item2</a></li>
<li><a href="">item3</a></li>
<li><a href="">item4</a></li>
</ul>
</div>
</body>
</html>