【发布时间】:2018-07-18 22:18:17
【问题描述】:
我有一组元素在包含的 div (.info) 中淡入淡出(一个接一个)。一些元素在出现时会留在容器内,而另一些元素会溢出容器,这不是首选。
当这种情况发生时,我想应用某种水平/自动滚动效果,这样它就可以显示溢出文本元素的开始到结束,同时仍然保持在一行上。有没有办法用 JQuery 来完成这个?
这是我迄今为止所取得的进展的简要说明:
(function() {
var tab = $(".info .tab");
var tabIndex = -1;
function showNextTab() {
++tabIndex;
tab
.eq(tabIndex % tab.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextTab);
}
showNextTab();
})();
.info {
background: skyblue;
display: inline-block;
line-height: 1;
width: 500px;
padding: 20px;
box-sizing: border-box;
}
.info .tab {
display: none;
}
h2.tab {
margin: 0;
padding: 0;
border: 0;
white-space: nowrap;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="info">
<h2 class="tab">This is the first line.</h2>
<h2 class="tab">This is the second line.</h2>
<h2 class="tab">This is the third line (which is longer than the first and second line.)</h2>
<h2 class="tab">This is the fourth line (which is longer than the first, second, and third line.)</h2>
</div>
更新:添加了滚动效果/仍在排除故障
这是一个更新的 sn-p,应用了最近的建议:
var myVar = "";
(function() {
var tab = $(".info .tab");
var tabIndex = -1;
function showNextTab() {
++tabIndex;
myVar = setInterval(myTimer, 1000);
tab
.eq(tabIndex % tab.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextTab);
}
showNextTab();
})();
function myTimer() {
var leftPos = $(".info").scrollLeft();
$(".info").animate({
scrollLeft: leftPos + 200
}, 800);
myStopFunction();
}
function myStopFunction() {
clearInterval(myVar);
}
.info-wrap {
background: skyblue;
display: inline-block;
line-height: 1;
width: 500px;
padding: 20px;
}
.info {
display: inline-block;
line-height: 1;
width: 500px;
overflow: hidden;
}
.info .tab {
display: none;
}
h2.tab {
margin: 0;
padding: 0;
border: 0;
line-height: 1;
white-space: nowrap;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<duv class="info-wrap">
<div class="info">
<h2 class="tab">This is the first line.</h2>
<h2 class="tab">This is the second line.</h2>
<h2 class="tab">This is the third line (which is longer than the first and second line.)</h2>
<h2 class="tab">This is the fourth line (which is longer than the first, second, and third line.)</h2>
</div>
</div>
问题1:为什么第四个<h2 class="tab">元素没有从头开始滚动?它似乎从中间点开始,向右。
问题2:如何修改左滑动画的速度?我试图了解myVar = setInterval(myTimer, 1000); 的目标是什么,以及scrollLeft: leftPos + 200}, 800);。
【问题讨论】:
标签: javascript jquery animation scroll jquery-animate