[英]How do I optimize this Javascript function?
I have a procedure so that my top nav has a different style if the user is scrolled near the top of the page or farther down from: 我有一个程序,如果用户滚动到页面顶部附近或远离页面顶部,则我的顶部导航具有不同的样式:
/* 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');
}
};
The problem is that I realize this is efficient because class
of navbar-default
is being added or removed a small number of times with respect to the number of times that onscroll
is invoked. 问题是我意识到这很有效,因为相对于调用
onscroll
的次数, navbar-default
class
的添加或删除次数很少。 I also realized that I need to change an image in the nav depending on whether or not scrolling is happening, so I would then have essentially 我还意识到,我需要根据是否正在滚动来更改导航中的图像,因此,基本上
/* 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');
}
};
which is even more ridiculous. 这更加荒谬。 How can I fumigate this room full of code smell?
我如何熏制充满代码气味的房间?
Here are some suggestions: 这里有一些建议:
Use css to change the toggle between images instead of changing the img source based on the class of the nav-default
使用CSS更改图像之间的切换,而不是根据
nav-default
的类更改img源
// 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; }
More advanced possibilities: 更高级的可能性:
(I don't personally know if this boosts performance but you could try it) (我个人不知道这是否可以提高性能,但是您可以尝试一下)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.