我想在mousewheel事件上创建一个自定义滑块,我的问题是如何才能在我的页面上完成每个滚动并在我的'ul li'上添加一个活动类并逐个递增,如:
if ($('scroll') === 1, function() {
$('ul li:first-child').addClass('active');
});
if ($('scroll') === 2, function() {
$('ul li:nth-child(2)').addClass('active');
});
ul li{
height:20px;
width:20px;
background:blue;
margin:5px;
list-style:none
}
ul li.active{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
答案 0 :(得分:1)
此语法不起作用:
if (value === other value, function() {
});
if
语句的正确语法如下:
if (value === other value) {
// execute code in here
}
另外,你有这个:
$('scroll') === 1
这里,$('scroll')
是一个jQuery函数,用于选择<scroll>
HTML元素(不存在)。
相反,您可以使用window.scrollY
在JavaScript中检测网页的滚动位置,返回the number of pixels that the document is currently scrolled down from the top。例如:
if (window.scrollY < 100) {
$('ul li:first-child').addClass('active');
} else if (window.scrollY < 200) {
$('ul li:nth-child(2)').addClass('active');
}
答案 1 :(得分:1)
基于this answer:,您可以执行以下操作:
var scrollable = $('ul li').length - 1,
count = 0;
$('body').bind('mousewheel', function(e) {
if (e.originalEvent.wheelDelta / 120 > 0) {
if (scrollable >= count && count > 0) {
$('.active').removeClass('active').prev().addClass('active');
count--
} else {
return false;
}
} else {
if (scrollable > count) {
$('.active').removeClass('active').next().addClass('active');
count++
} else {
return false;
}
}
})
ul li {
height: 20px;
width: 20px;
background: blue;
margin: 5px;
list-style: none
}
ul li.active {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>