jquery單頁錨點移動,jquery頁錨移動
有很多企業網站的官網都有使用這種錨點的方式移動到指定位置的功能。
首先點擊跳轉的元素需新增一個location屬性,這個location屬性值就是指定跳轉位置元素的name值。
調用方法:
1、直接對頁面上所有錨點元素添加事件。
jQuery.Location({...});2、單個元素錨點。
$("..").Location({...});範例:
<!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><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>無標題文檔</title><script type="text/javascript" src="jquery-1.9.1.js"></script><style type="text/css">*{margin:0;padding:0;font-family:微軟雅黑}.body_top{height:40px;background:#3399CC;position:fixed;left:0;top:0;width:100%}.body_top ul{width:auto;list-style:none;height:40px;z-index:9999}.body_top ul li{float:left;height:30px;line-height:30px;width:100px;margin-left:50px;background:#FFFFFF;text-align:center;margin-top:5px;color:#6F6F6F;border-radius:30px;font-size:10pt;cursor:pointer;box-shadow:inset 0 0 3px #AFAFAF}.body_center{height:auto;margin-top:41px;}.body_center .sub_meau_1{height:200px;background:#EFEFEF;border:1px solid #AFAFAF;}.body_center .sub_meau_2{height:400px;background:#DFDFDF;border:1px solid #AFAFAF;}.body_center .sub_meau_3{height:600px;background:#CFCFCF;border:1px solid #AFAFAF;}.body_center .sub_meau_4{height:800px;background:#BFBFBF;border:1px solid #AFAFAF;}.body_center .sub_meau_5{height:1000px;background:#AFAFAF;border:1px solid #AFAFAF;}</style></head><body><div class="body_top"><ul><li location="sub_meau_1">子功能表一</li><li location="sub_meau_2">子功能表二</li><li location="sub_meau_3">子功能表三</li><li location="sub_meau_4">子功能表四</li><li location="sub_meau_5">子功能表五</li></ul></div><div class="body_center"><div class="sub_meau_1" name='sub_meau_1'></div><div class="sub_meau_2" name='sub_meau_2'></div><div class="sub_meau_3" name='sub_meau_3'></div><div class="sub_meau_4" name='sub_meau_4'></div><div class="sub_meau_5" name='sub_meau_5'></div></div><div class="body_bottom"></div></body><script type="text/javascript">//jquery連結;(function($){//所有連結jQuery.Location = function(options){var defaultOptions = {time:1000,layer:null //菜單浮層,jquery對象},settings = jQuery.extend(defaultOptions,options || {}),//查詢所有有location屬性的元素locations = $("[location]");for(var i=0,maxLen=locations.length;i<maxLen;i++) {locations.eq(i).Location(settings);}};//指定單個連結jQuery.fn.Location = function(options){var defaultOptions = {time:1000,layer:null}; var settings = jQuery.extend(defaultOptions,options || {}),name = $(this).attr("location"),target = $("*[name="+name+"]"),top = target.offset().top;if(settings.layer !== null && settings.layer.length !== 0) {top = top - settings.layer.innerHeight();}return this.each(function(){$(this).click(function(){$("body,html").stop(false,true).animate({scrollTop:top},settings.time);});});};})(jQuery);//調用方法jQuery.Location({time:500,layer:$(".body_top")});</script></html>
樣式顯示: