2

I am using the following code to track the scrolling and I want to put the selected element variables outside the event handler so they are not called each time the user scrolls thereby saving resources. The following only works if I put the first two variables inside the event handler:

    var recommend_con_list=$(".recommend_con_list")
    var recommend_con=$('.recommend_con')
    $(window).scroll(function () {

        var y=$(window).scrollTop()
        if(y > 82){
            recommend_con.css({position:"fixed",top:"0"})
        }else{
            recommend_con.css({position:"",top:""})
        }
    });
4

1 回答 1

1

如果你想进一步优化,我会使用这个:

$(document).ready(function () {
    var recommend_con_list = $(".recommend_con_list").get(),
        recommend_con = $('.recommend_con').get(),
        $window = $(window);

    $window.scroll(function () {
        var y = $window.scrollTop();
        if (y > 82) {
            for (var i = 0, j = recommend_con.length; i < j; i++) {
                recommend_con[i].classList.add("special");
            }
        } else {
            for (var i = 0, j = recommend_con.length; i < j; i++) {
                recommend_con[i].classList.remove("special");
            }
        }
    });
});

使用这个 CSS:

<style type="text/css">
    .special {
        position: fixed;
        top: 0;
    }
</style>
于 2013-05-09T05:20:26.160 回答