使用jQuery,你可以在單擊菜單時對目標頁面進行POST調用。
POST數據將包含您要滑動到的div的ID。
在您的目標頁面上,使用您的服務器語言(php,asp)在js變量中輸出該id,並使用jQuery將該id輸出到準備好文檔的幻燈片上。
然後你將有一個乾淨的網址,並滾動到你的div頁面。編號:代碼如下!
當點擊一個菜單項時,讓我們使用jquery創建一個POST到目標頁面。我們將添加一個類,讓我們說,「mymenuitem」。我們將把這個類添加到菜單中的鏈接中。因此,我們將有
<li><a href="YOURTARGETPAGE.HTML#scroll-to" onClick="javascript:return false;" class="mymenuitem">Information about us</a></li>
(的的onClick停止鏈接從手動重定向) 和一個空的形式(把它放在<體>後)
<form id="slidinganchorform" method="post" action="YOURTARGETPAGE.HTML"></form>
然後我們將創建neccessary jQuery的,所以當單擊類「mymenuitem」的< a>標籤,我們將向目標頁面發佈POST。
<script type="text/javascript">
jQuery(document).ready(function(){
$(".mymenuitem").click(function() {
// we will split the clicked href's value by # so we will get [0]="about" [1]="scroll-to"
var the_anchor_id_to_scroll_to = $(this).attr("href").split('#')[1];
// lets do the POST (we WILL TRIGGER a normal FORM POST while appending the correct id)
$("#slidinganchorform").append('<input type="hidden" name="anchorid" value="'+ the_anchor_id_to_scroll_to + '">');
$("#slidinganchorform").submit();
});
});
</script>
那麼在我們YOURTARGETPAGE.HTML我們會碰到這樣的(假設我們使用PHP)
<head>
<!-- make sure your jquery is loaded ;) -->
<?php
if($_POST['anchorid']!='')
{
?>
<script type="text/javascript">
jQuery(document).ready(function(){
// lets get the position of the anchor (must be like <a name="scroll-to" id="scroll-to">Information</a>)
var thePositiontoScrollTo = jQuery('#<?php echo $_POST['anchorid']; ?>').offset().top;
// Lets scroll
jQuery('html, body').animate({scrollTop:thePositiontoScrollTo}, 'slow');
});
</script>
<?php
}
?>
</head>
務必正確的ID必須存在;)
<a name="scroll-to" id="scroll-to">Information about us or whatever...</a>
(刪除你的舊代碼,因爲我改變了一些變量名稱,如果以前版本中有部分代碼,將會很難調試。從頭開始編寫一切)
這可能是比它的價值更麻煩,但你可以使用[History.js](http://balupton.github.io/ history.js /演示/)。 – bdesham