问题描述
我有这个代码,它完全按照我的意愿工作。菜单栏位于顶部并识别它所在的部分。您可以单击黄色菜单中的链接在各部分之间移动。
I have this code and it works exactly as I want. The menu bar sits on top and recognizes the section it is on or in. You can click the links in the yellow menu to move between the sections.
$(function(){
$(function () {
var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $select.length ? $select.offset().top : 0;
$window.scroll(function () {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
$('body').css('padding-top', $select.height());
} else if (currentScrollTop <= init) {
isFixed = false;
$select.css('position', 'relative');
$('#select span').removeClass('active');
$('body').css('padding-top', 0);
}
//active state in menu
$('.section').each(function(){
var eleDistance = $(this).offset().top;
if (currentScrollTop >= eleDistance-$select.outerHeight()) {
var makeActive = $(this).attr('id');
$('#select span').removeClass('active');
$('#select span.' + makeActive).addClass('active');
}
});
});
$(".nav").click(function (e) {
var divId = $(this).data('sec');
$('body').animate({
scrollTop: $(divId).offset().top - $select.height()
}, 500);
});
});
然而,只要您开始在框中添加任何内容,代码本身就会变得非常迟缓。我想知道是否有机会优化代码并让它运行得更顺畅。
However, the code itself gets quite laggy as soon as you start putting any content in the boxes. I wondered if there is any opportunity to optimize the code and make it run a bit smoother.
推荐答案
你遇到的问题是你反复更改页面布局属性(通过动画)和查询页面布局属性(在滚动处理程序中),从而触发大量的。
The problem you have is that you're repeatedly changing page layout properties (via the animation) and querying page layout properties (in the scroll handler), thus triggering a large number of forced layouts.
如果我正确理解你的代码你可以通过在点击动画期间禁用滚动处理程序来获得一个很大的改进,而不是在没有检查的情况下触发效果(在点击的元素上设置活动类)。
If i understand your code correctly you could get a big improvement by disabling the scroll handler during the click animation and instead triggering the effects with no checks made (set the active class on the clicked element).
这篇关于滞后JavaScript - 优化或更便宜功能的机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!