Skip to content

Instantly share code, notes, and snippets.

@oksep
Created February 15, 2016 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oksep/a7747de15000e31041fa to your computer and use it in GitHub Desktop.
Save oksep/a7747de15000e31041fa to your computer and use it in GitHub Desktop.
锚链接平滑滚动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>锚链接平滑滚动</title>
<meta name="description" content="">
<meta name="keywords" content="">
<style type="text/css">
* {
margin: 0;
padding: 0
}
html,body {
height: 100%;
min-height: 100%;
}
.top {
width: 100%;
height: 40px;
line-height: 40px;
background: rgba(0, 0, 0, .6);
position: fixed;
z-index: 9;
}
a {
color: #fff;
text-align: center;
text-decoration: none;
}
.top a {
display: inline-block;
width: 20%;
}
.top a:hover {
background: rgba(0, 0, 0, .4);
}
.page {
width: 100%;
height: 100%;
min-height: 100%;
background: #3C98FF;
text-align: center;
}
h1 {
color: #fff;
padding-top: 20%;
}
</style>
</head>
<body>
<div class="top">
<a href="#div-1">div-1</a>
<a href="#div-2">div-2</a>
<a href="#div-3">div-3</a>
<a href="#div-4">div-4</a>
</div>
<div id="div-1" class="page">
<h1>第一页</h1>
</div>
<div id="div-2" class="page">
<h1>第二页</h1>
</div>
<div id="div-3" class="page">
<h1>第三页</h1>
</div>
<div id="div-4" class="page">
<h1>第四页</h1>
</div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$('a[href*=#]').click(function(event) {
// 此处正则用于转换带页面URL的锚点,如 http://abc.html#div,具体正则格式据实际情况而定
var targetId = $(this).attr('href').replace(/\w+.html/,'');
$("html,body").animate({scrollTop: $(targetId).offset().top}, 1000);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment