我想在每个卷轴上操作sum的值。如果我向下滚动,值应该增加到我想要的任何值,如果我向上滚动,值应该减少到我想要的任何值,只要它不小于零。
$(window).on('wheel', function(e) {
var delta = e.originalEvent.deltaY;
var sum = 0;
if (delta > 0){
sum++;
console.log("going down");
console.log(sum);
} else {
//sum--;
console.log("going up");
}
return false;
});
html,
body{
height: 100%;
}
#firstbox{
background: red;
}
#second_box{
background: blue;
}
#third_box{
background: black;
}
.general{
width: 100%;
height: 100%;
}
header{
width: 100%;
height: 100%;
}
img{
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="firstbox" class="general">
<header><img src="https://cdn.pixabay.com/photo/2017/06/05/20/10/blue-2375119_960_720.jpg" alt="image here"></header>
</div>
<div id="second_box" class="general">
</div>
<div id="third_box" class="general">
</div>
此时,该值不会增加/减少,而是不断重复。
如何在每个卷轴上操作(增加/减少) sum的值?
提前感谢
发布于 2019-03-14 13:59:07
将var sum = 0
移出触发器函数。它在您的实现中的每个滚动上都设置为零:
var sum = 0;
$(window).on('wheel', function(e) {
var delta = e.originalEvent.deltaY;
if (delta > 0){
sum++;
console.log("going down");
console.log(sum);
} else {
if (sum > 0) {
sum--;
}
console.log("going up");
console.log(sum);
}
return true;
});
html,
body{
height: 100%;
}
#firstbox{
background: red;
}
#second_box{
background: blue;
}
#third_box{
background: black;
}
.general{
width: 100%;
height: 100%;
}
header{
width: 100%;
height: 100%;
}
img{
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="firstbox" class="general">
<header><img src="https://cdn.pixabay.com/photo/2017/06/05/20/10/blue-2375119_960_720.jpg" alt="image here"></header>
</div>
<div id="second_box" class="general">
</div>
<div id="third_box" class="general">
</div>
发布于 2019-03-14 14:04:40
var sum = 0;
$(window).on('wheel', function(e) {
var delta = e.originalEvent.deltaY;
if (delta > 0){
sum++;
console.log("going down");
console.log(sum);
} else {
sum--;
console.log("going up");
console.log(sum);
}
return false;
});
html,
body{
height: 100%;
}
#firstbox{
background: red;
}
#second_box{
background: blue;
}
#third_box{
background: black;
}
.general{
width: 100%;
height: 100%;
}
header{
width: 100%;
height: 100%;
}
img{
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="firstbox" class="general">
<header><img src="https://cdn.pixabay.com/photo/2017/06/05/20/10/blue-2375119_960_720.jpg" alt="image here"></header>
</div>
<div id="second_box" class="general">
</div>
<div id="third_box" class="general">
</div>
全局声明sum的值将解决更多的问题,更多与作用域相关的事情,请通过以下链接https://www.geeksforgeeks.org/understanding-variable-scopes-in-javascript/
https://stackoverflow.com/questions/55164317
复制