JS的scrollIntoView学习
scrollIntoView(alignWithTop) 滚动浏览器窗口或容器元素,以便在当前视窗的可见范围看见当前元素。如果alignWithTop为true,或者省略它,窗口会尽可能滚动到自身顶部与元素顶部平齐。-------目前各浏览器均支持,其实就这个解释来说,我觉得还是不够的,最好还是又图对吧,来看下图,更好理解:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a onClick="onc()">dasdasd</a>
<div style="width:400px; height:400px; border: 1px solid #f00;"></div>
<div id="nn" style="border:1px solid #666">
<div style="height:900px;">sadasdasd</div>
</div>
</body>
<script type="text/javascript">
//作为一个事件的函数来被调用
function onc () {
var dd = document.getElementById("nn").scrollIntoView(true); //这个意思其实就是将这个元素到顶部来浏览器窗口的顶部来显示
}
</script>
</html>
如图:
这个id为nn的div就会到浏览器窗口的顶部显示;
至于false,你可以自行去尝试一下,效果也是很明显的,
=========================================
通过这个函数做的一个小实例,锁定网页的导航条,然后点击导航,调到指定的div,这个功能在一般的网页设计中是很常见的,看代码:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>nav测试</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
*{margin:0; padding:0}
body{width:960px; height:2000px; margin:0 auto; border: 1px dotted #432432;}
ul,li{list-style-type: none;}
a{text-decoration: none;}
.nav{border:1px solid #000;
height:30px;
z-index:9999;
position:fixed ;
top:0px;
_position:absolute;
_top:expression(documentElement.scrollTop + "px");
}
.nav ul li{
float:left;
font-size: 16px;
line-height: 30px;
padding:0px 63px;
}
.nav ul li:hover{
background: #23ded3;
}
#main{
height:1000px;
border:1px solid #f00;
margin-top:30px;
}
#div1{
height:400px;
border: 1px solid #ccc;
}
#div2{
height:400px;
border: 1px solid #ccc;
}
#div3{
height:400px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="headr">
<div class="nav">
<ul>
<li><a>首页</a></li>
<li><a onclick="onc()">你好</a></li>
<li><a>很好</a></li>
<li><a>他好</a></li>
<li><a>真的</a></li>
<li><a>哦哦</a></li>
</ul>
</div>
</div>
<div id ="main" style="width:960px; height: auto;">
<div id="div1">
<p>我是div1的内容</p>
</div>
<div id="div2">
<p>我是div2的内容</p>
</div>
<div id="div3">
<p>我是div3的内容</p>
</div>
</div>
<div id ="footr"></div>
</body>
<script type="text/javascript">
var dHeight = document.documentElement.clientHeight;
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
div1.style.height = dHeight - 30 + "px"; //通过一个js动态的来确定每个div的高度,还可以通过循环来实现,这里就不加了,各位自己可尝试
div2.style.height = dHeight -30 + "px";
div3.style.height = dHeight -30 + "px";
var li = document.getElementsByTagName(