我正在尝试编写一个jQuery脚本,该脚本将在<p>
父项中不断滚动这些<div>
标记。我从this site得到了这个想法。
function shuffle(){
$('#wrapper > p').each(function(){
h = ($(this).offset().top + 130);
if( h > 500 ){
console.log(h);
$(this).css ('top', 0 );
return;
}
if( h == 270 ){
$(this).addClass('current' );
}
if( h == 360 ){
$(this).removeClass('current' );
}
$(this).animate({
top: h,
easing: 'easeIn'
}, 500, '');
if( h > 1350 ){
$(this).css ('top', 0 );
}
});
window.setTimeout(shuffle, 2500);
}
var i = 0;
$('#wrapper > p').each(function(){
starter = $(this).css('top', ((i * 90) ) + 'px' );
starterWhite = ($(this).offset().top + 130);
if((i*90) == 270)
$(this).addClass('current');
$(this).css('top', starter );
i++;
});
window.setTimeout(shuffle, 2000);
#wrapper {
height: 500px;
overflow: hidden;
position: relative;
}
p {
position: absolute;
margin: 0;
padding: 0;
}
.current {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
</div>
问题是当我尝试滚动<p>
标签重叠时,突出显示的标签不会改变。知道如何让它工作吗?到目前为止我所得到的Here's a JSFiddle。
答案 0 :(得分:3)
检查this:
// Constants, you can play with it
var STEP = 90;
var CURRENT_INDEX = 3;
// Variables for calculating
var currentTop = STEP * CURRENT_INDEX;
var nextForCurrentTop = STEP * (CURRENT_INDEX + 1);
var $numbers = $('#wrapper > p');
// In this case = 7
var count = $numbers.length;
var secondToLastTop = STEP * (count - 1);
$numbers.each(function(i) {
var $this = $(this);
$this.css('top', i * STEP + 'px');
if (i === CURRENT_INDEX) {
$this.addClass('current');
}
});
window.setTimeout(shuffle, 2000);
function shuffle() {
$numbers.each(function() {
$this = $(this);
// Calculating the new position of the element
h = parseInt($this.css('top')) + STEP;
// In this case = 540
if (h > secondToLastTop) {
$this.css('top', 0);
return;
}
// In this case visually = 3rd element
if (h === currentTop) {
$this.addClass('current');
}
// In this case visually = 4th element
if (h === nextForCurrentTop) {
$this.removeClass('current');
}
$this.animate({
top: h,
easing: 'easeIn'
}, 500, '');
});
window.setTimeout(shuffle, 2500);
}
#wrapper {
height: 500px;
overflow: hidden;
position: relative;
}
p {
position: absolute;
margin: 0;
padding: 0;
}
.current {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
</div>
我改进并评论了您示例中的代码,删除了幻数。你可以玩常数。