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. 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
// 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.