网站建设设计/网站设计/html锚点定位四种方法

2024-03-29   浏览量:

网站建设设计/网站设计/html锚点定位四种方法
 
第一种方法,也是最简单的方法是锚点用<a>标签,在href属性中写入DIV的id。如下:
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 800px;
width: 400px;
border: 2px solid black;
}
h2 {
position: fixed;
margin:50px 500px;
}
</style>
</head>
<body>
<h2>
<a href="#div1">to div1</a>
<a href="#div2">to div2</a>
<a href="#div3">to div3</a>
</h2>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
</body>
</html>
 

网站建设设计,网站设计
 
 
第二种方法是在js事件中通过window.location.hash="divId"跳转,但地址也会发生变化,感觉跟第一种方法没区别,甚至更麻烦。
第三种方法是用animate属性,当点击锚点后,页面滚动到相应的DIV。接着上面的代码,具体添加如下代码:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#div1Link").click(function() {
$("html, body").animate({
scrollTop: $("#div1").offset().top }, {duration: 500,easing: "swing"});
return false;
});
$("#div2Link").click(function() {
$("html, body").animate({
scrollTop: $("#div2").offset().top }, {duration: 500,easing: "swing"});
return false;
});
$("#div3Link").click(function() {
$("html, body").animate({
scrollTop: $("#div3").offset().top }, {duration: 500,easing: "swing"});
return false;
});
});
</script>