html 页面内锚点定位及跳转方法总结
来源:互联网 发布:人工智能的未来 pdf 编辑:程序博客网 时间:2024/06/05 04:42
原文出处:http://www.cnblogs.com/zqifa/p/html-1.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>
这种方法的缺点是点击锚点之后,浏览器的URL会发生变化,如果刷新可能会出现问题。
第二种方法是在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>
注意:运行上面的脚本的之前,先将为锚点增加相应的id,同时去掉href属性。
$("html, body")可以替换为响应的div,如果不起作用,试着给该div增加overflow:scroll属性。
另外,脚本可以进一步优化,自己来试试
这样做的好处是:URL地址不会变,同时点击锚点时会自动响应scroll事件,不需要重新绑定。
缺点是:如果页面复杂的话,偏移值可能会发生变化需要算法辅助。
第四种方法是用js的srollIntoView方法,直接用:
document.getElementById("divId").scrollIntoView();
这种方法的好处,是URL不会变,同时能够响应相应的scroll事件,不需要算法什么的。
(例子可参考这里: html 页面内锚点定位及跳转方法总结)
推介大家用第四种,我依次试了前三种,都有各种问题。
#2楼
- html 页面内锚点定位及跳转方法总结
- html 页面内锚点定位及跳转方法总结
- html 页面内锚点定位及跳转方法总结
- html 页面内锚点定位及跳转方法总结
- 【转】html 页面内锚点定位及跳转方法总结
- 页面内锚点定位及跳转方法总结
- 页面内锚点定位及跳转方法总结
- 页面内锚点定位及跳转方法
- jsp,JavaScript,HTML跳转页面方法总结
- HTML页面跳转方法及代码
- 页面跳转方法总结
- 页面跳转方法总结
- html页面跳转方法集合
- HTML页面跳转的方法
- html js点击按钮滚动跳转定位到页面指定位置(DIV)的方法代码
- 页面跳转方法总结大全
- 页面跳转实现方法总结
- 页面跳转方法总结大全
- tornado中参数的获取
- Vue——props数据传递
- Eclipse导入 项目文件显示红感叹号的解决方法
- jQuery初识与环境搭建(一)
- macOS上搭建python环境
- html 页面内锚点定位及跳转方法总结
- hdu 1041 Computer Transformation(规律+大数)
- 教你如何批量复制速卖通商品到Shopify自建商店
- 反汇编定位代码崩溃位置_3
- Sublime3下运行含有中文字符的Python程序报错:[Decode error
- Java 中 MessageFormat.format 用法
- Nginx安装配置以及https
- iOS高德地图 指南针(罗盘)不转的解决方法
- 深入理解单例模式
var id_number=$(".unit").index(this)+1;
var offset_from=$("#units_intro").scrollTop();
document.getElementById("unit"+id_number).scrollIntoView();
var offset_to=$("#units_intro").scrollTop();
$("#units_intro").scrollTop(offset_from);
$("#units_intro").animate({
scrollTop: offset_to }, {duration: 500,easing: "swing"});
return false;
原理就是先滚动到目标量出偏移值,再回去来个动画版。