您正在为所有li项添加活动类。
$('.blockList li').each(function(index) {
setTimeout(()=>{
$(this).addClass('active');
}, 200*index);
});
目标:目标
在短期内。您基本上是向每个列表元素添加两次活动类。因为你是在乞讨时加上它,然后再加上60%的补偿。
一种解决办法可能是
所以它会检查它的
位置->滚动时检查是否到达任何元素->如果达到,则将活动类添加到响应ID。
var p = $( "#red" ).position;
var Positions = {top: p.top};
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
然后比较它们,如果它到达元素。
然后获取其id并添加
.active
类到
#red li
,不是李将军。
在这种情况下我会怎么做:
var global_list = {}; var elemCount = 0;
$(document).ready(function() {
//call initFunc, after its complete, call elimination (so it would check on load) and then set on scroll.
initFunc(function() {
elimination();
$(document).on('scroll', function() { elimination() });
});
//This function is basicaly your startup.
function initFunc(int) {
$('.blockList').each(function() {
var p = $(this).position(); //Lets get its position.
var id = $(this).attr('id'); //Lets get its ID
global_list[id] = p.top; //Lets asign ID -> topPosition, so { first: 8 }...
elemCount++;
});
int();
}
//This assigns needed stuff for allready reached objects.
function elimination() {
if(elemCount != 0) { //Did we allready show all elements?
var cb = $(this).scrollTop() + ($(this).height()), ct = $(this).scrollTop(); //Gets top position, and bottom.
var cP = ct + ((cb - ct)/2); //Gets your center point of viewport - ad half screen size to top;
for(var k in global_list) { //Loop trough all element that are left and see if we did scroll.
if(global_list[k] <= cP) { //Lets check if user scolled to it.
var ic=0;
$('#'+k+' li').each(function() {
setTimeout(()=>{
$(this).addClass('active');
}, 200*ic);
ic++
});
delete global_list[k]; //Lets delete allready assigned classes
elemCount--; //Decreses elements count, so eventualy once all reached, it becomes 0;
}
}
}
}
});
#first {
height: 1000px;
}
#second {
height: 1000px;
}
.beatiful {
background: yellow;
}
.div_div li {
font-size: 1rem;
color: #000;
margin: 20px 0;
opacity: 0;
-webkit-transition: ease 0.4s;transition: ease 0.4s;
-webkit-transform: translateY(-15px);transform: translateY(-15px);
}
.div_div li.active {
opacity: 1;
-webkit-transform: translateY(0px);transform: translateY(0px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='div_div' id='first'>
<ul class="blockList" id='first'>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
</div>
<div class='div_div' id='second'>
<ul class="blockList" id='second'>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
</div>