有很多企业网站的官网都有使用这种锚点的方式移动到指定位置的功能。
首先点击跳转的元素需新增一个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}); </script> </html>
样式显示:
时间: 2024-09-20 18:23:58