[英]Can not access global variables inside a jQuery event handler
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:""})
}
});
If you want to optimize further, I would use this: 如果您想进一步优化,可以使用以下方法:
$(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");
}
}
});
});
With this CSS: 使用此CSS:
<style type="text/css">
.special {
position: fixed;
top: 0;
}
</style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.