除了錨鏈接,還有什麼辦法實現定位?
阿新 • • 發佈:2018-11-24
1.使用scrollIntoView方法
<li><a onclick="javascript:document.getElementById('user1').scrollIntoView();">user1</a></li>
2.使用js,如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>錨點</title>
</head>
<body>
<ul>
<li><a href="javascript:void(0);" onclick="naver('A')">錨點A</a></li>
<li><a href="javascript:void(0);" onclick="naver('B')">錨點B</a></li>
<li><a href="javascript:void(0);" onclick="naver('C')">錨點C</a> </li>
<li><a href="javascript:void(0);" onclick="naver('D')">錨點D</a></li>
</ul>
<div style="background-color: #f60; height: 400px;" id="A">
AAA
</div>
<div style="background-color: #f06; height: 400px;" id="B">
BBB
</div>
<div style="background-color: #60f; height: 400px;" id="C">
CCC
</div>
<div style="background-color: #06f; height: 400px;" id="D">
DDD
</div>
<script>
//設定錨點
function naver(id){
var obj = document.getElementById(id);
var oPos = obj.offsetTop;
return window.scrollTo(0, oPos-36);
}
</script>
</body>
</html>