jq实现点击导航栏滚动到对应位置(锚点跳转滑动效果)和导航栏菜单项随页面滚动而变化

您所在的位置:网站首页 导航栏代码颜色可变动的 jq实现点击导航栏滚动到对应位置(锚点跳转滑动效果)和导航栏菜单项随页面滚动而变化

jq实现点击导航栏滚动到对应位置(锚点跳转滑动效果)和导航栏菜单项随页面滚动而变化

2024-01-23 00:10| 来源: 网络整理| 查看: 265

点击导航栏滚动到对应位置(延迟效果)

1.跳转实现

跳转

如上图两行代码便可实现a标签‘#’后面跟对应的id值 2.锚点跳转滑动效果

.btn{ position:fixed; right:10%; top:20%; } .btn a{ display:block; width:80px; text-align:center; color:#fff; } 跳转a 跳转b 跳转c 跳转d

html部分 记得再body底部先引入jq再引入下面的js代码

$('a[href*=#],area[href*=#]').click(function() { //若报错则改为$(document).on('click', 'a[href^="#"]', function () { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');//获取到点击对应id的元素 if ($target.length) { var targetOffset = $target.offset().top; $('html,body').animate({ //滑动效果主要用到jq的animate函数 scrollTop: targetOffset },500); return false; } } });

js部分

这样就可以实现导航栏的跳转滑动效果啦

导航栏菜单项随页面滚动而变化

1.实现原理及方法

.btn{ position:fixed; right:10%; top:20%; } .btn a{ display:block; width:80px; text-align:center; color:#fff; } 跳转a 跳转b 跳转c 跳转d

用回上面贴出的代码。通过比较a元素的偏移量与页面偏移量,和b元素下的偏移量与滚轮偏移量的大小,判断a元素是否进入页面可视区域,其他元素同理。 我们先了解一下下面的一些方法

var winPos = $(window).scrollTop(); //屏幕位置 var winHeight = $(window).height(); //屏幕高度 var objPos = obj.offset().top //元素位置 var objHeight = obj.Height() //元素高度

$(window).scrollTop() :当前页面滚到的位置。 $(window).height() :当前页面的可视高度。 obj.offset().top:当前元素的顶部位置距离整个页面顶部的实际高度。 obj.Height() :元素高度

补充: 在jQuery中 width() 方法用于获得元素宽度; innerWidth() 方法用于获得包括内边界(padding)的元素宽度 outerWidth() 方法用于获得包括内边界(padding)和边框(border)的元素宽度 如果outerWidth() 方法的参数为true则外边界(margin)也会被包括进… height()、.innerHeight()和.outerHeight() 和W3C的盒模型相关的几个获取元素尺寸的方法对应宽度获取方法一样,在此不详述。

这里主要用到 $(window).scrollTop() 跟obj.offset().top 方法 贴代码: html

.btn{ position:fixed; right:10%; top:20%; } .btn a{ display:block; width:80px; text-align:center; color:#dfdfdf; } .btn .active{ color:#fff; } 跳转a 跳转b 跳转c 跳转d // js $(window).scroll(function(event){ checkscroll() }); function checkscroll(){ var winPos = $(window).scrollTop(); //屏幕位置 var NodePos = [$('#a').offset().top,$('#b').offset().top,$('#c').offset().top,$('#d').offset().top],//提前获取好元素位置 length = NodePos .length; //console.log(NodePos) if(winPos for(var i = 1;i $('.btn a').removeClass('active'); $('.btn a:nth-child('+(i+1)+')').addClass('active'); break; } } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3