昨天收到一個任務,就是調整頁面定位的問題,我仔細研究了一下,開始感受很複雜,須要用js控制的,可是後來才發現是一個簡單的css錨的用法,無論怎麼,問題解決了,看了許多js的相關知識,也算是收益不小,這裏總結一下,以便後來溫習。 javascript
首先看一下效果: css
從本頁面的「我要提問」的連接跳轉到下一個頁面的頁面顯示效果 html
或者是進入baidu百科隨便點一個連接,能夠定位到下面頁面的某個位置這樣一個效果。 java
一下是實現原理:僅僅是在a標籤中使用了#post字段。 post
例如:href="a.html#post" 測試
css僞類中對a的使用不少,這裏就是使用了a的特性,實現代碼以下: this
<a href="#mypage">跳到定位位置吧</a> xml
<a name="mypage">這個是我要定位的地方</a>//同頁面的定位 htm
<div id="mypage">這個是另外一種定位效果</div>//不一樣頁面間的跳轉定位 ip
以上三句就是主要的實現代碼,在第一句中設置要定位的地方,在第二句中使用name與之對應,這樣頁面就能夠直接定位到第二句的位置了;或者是使用第一句和第三句,實現不一樣頁面間的定位設置。
原理說完,下面具體的測試代碼,趕忙來測試一下效果吧。
a.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript 控制滾動條示例代碼</title>
<style type="text/css">
.bigbox{border:1px solid red;width:500px;height:300px;background-color:#336699;margin:10px;}
#first{text-align:center;margin:10px;}
</style>
<script type="text/javascript">
function test(){
//this.scroll(0,document.body.scrollHeight);
}
//window.scrollTo(0,document.body.scrollHeight);
</script>
</head>
<body>
<div id="first">
<a href="#mylocation" name="mylocation3">定位到同頁面</a>
<a href="b.html#mylocation">定位到不一樣頁面</a>
<div class="bigbox">women</div>
<div class="bigbox">women</div>
<a name="mylocation">定位到這裏,中部,看看效果吧</a>
<div class="bigbox">women</div>
<div id="mylocation2">women</div>
<a href="#mylocation3">定位到同頁面頂部</a>
<div class="bigbox">women</div>
</div>
</body>
</html>
b.html:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript 控制滾動條示例代碼</title>
<style type="text/css">
.bigbox{border:1px solid red;width:500px;height:300px;background-color:#336699;margin:10px;}
</style>
</head>
<body>
<a href="a.html#mylocation2">定位到不一樣頁面</a>
<div class="bigbox">women</div>
<div id="mylocation">定位到這裏,這是第二個頁面的定位,看看效果吧</div>
<a href="a.html#mylocation2">定位到不一樣頁面</a>
<div class="bigbox">women</div>
<div class="bigbox">women</div>
</body>
</html>
好了,這樣簡單的功能就實現了,其實開始的時候一直是向用js控制的,也就查了不少的資料,這個效果其實能夠使用js控制,那就應該算是經過js控制滾動條的位置來控制頁面加載定位位置的設定了,下面總結一下:
第一:使用js能夠控制css錨的設置:
window.location.hash="1"//1表示錨點的名字。例如上文中的id或者name。
第二:window.scrollTo(x,y);//x表示橫座標,y表示縱座標。例如window。scrollTo(0,400);
其餘js使用技巧:
window.location.href="a.html";
window.open//打開窗體
window.top.location//窗體最頂端的位置
iframe控制伏擊滾動條:
window.parent.scorllTo(X,Y);