如何优化此Javascript函数?
我有一个程序,如果用户滚动到页面顶部附近或更远的地方,我的顶部导航将具有不同的样式:如何优化此Javascript函数?,javascript,jquery,css,algorithm,event-handling,Javascript,Jquery,Css,Algorithm,Event Handling,我有一个程序,如果用户滚动到页面顶部附近或更远的地方,我的顶部导航将具有不同的样式: /* Handle the changing of the top nav on page scroll */ window.onscroll = function () { if ($(window).scrollTop() > 150) // 150 pixels from top triggers scrolling { $('.navbar-default').ad
/* Handle the changing of the top nav on page scroll */
window.onscroll = function ()
{
if ($(window).scrollTop() > 150) // 150 pixels from top triggers scrolling
{
$('.navbar-default').addClass('scrolling');
}
else
{
$('.navbar-default').removeClass('scrolling');
}
};
问题是,我意识到这是有效的,因为相对于调用onscroll
的次数,正在添加或删除navbar default
的class
。我还意识到,我需要根据是否发生滚动来更改导航中的图像,这样我就可以
/* Handle the changing of the top nav on page scroll */
window.onscroll = function ()
{
if ($(window).scrollTop() > 150) // 150 pixels from top triggers scrolling
{
$('.navbar-default').addClass('scrolling');
$('.navbar-default .navvar-brand img').attr('src','image1.jpg');
}
else
{
$('.navbar-default').removeClass('scrolling');
$('.navbar-default .navvar-brand img').attr('src','image2.jpg');
}
};
这更是荒谬。我如何才能熏蒸这个充满异味的房间?以下是一些建议:
- 将花括号与函数放在同一行,否则您可能会遇到自动分号插入的情况问题-
- 对图像使用精灵-
- 切换类
- 使用css更改图像之间的切换,而不是根据
nav default
// Something like this... .nav-default { background-image: url('spriteimage.jpg'); background-repeat: no-repeat; height: // height of first image here; background-position: // position of first image here; } .nav-default.scrolling { height: // height of second image here; background-position: // position of second image here; }
- 以小间隔(100ms)轮询以检查滚动条的位置,而不是每次有人滚动然后切换类时都进行检查
- 这将不那么快速/响应,但会更加一致(最坏情况:每100毫秒切换一次类)
- 将花括号与函数放在同一行,否则您可能会遇到自动分号插入的情况问题-
- 对图像使用精灵-
- 切换类
- 使用css更改图像之间的切换,而不是根据
nav default
// Something like this... .nav-default { background-image: url('spriteimage.jpg'); background-repeat: no-repeat; height: // height of first image here; background-position: // position of first image here; } .nav-default.scrolling { height: // height of second image here; background-position: // position of second image here; }
- 以小间隔(100ms)轮询以检查滚动条的位置,而不是每次有人滚动然后切换类时都进行检查
- 这将不那么快速/响应,但会更加一致(最坏情况:每100毫秒切换一次类)
- 以下是一些建议:
.addClass()
可能会先检查hasClass()
,以免重写HTML,所以这不应该是个问题。至于第二点,请使用CSS而不是img标记。这个问题的标题非常混乱。@Pointy我的意思是如何减少平均操作数,所以是“如何”而不是“为什么”…不,问题是“为什么”和“如何”.addClass()
可能会先检查hasClass()
,以免重写HTML,所以这不应该是个问题。至于第二点,使用CSS而不是img标记。