我对 jQuery 完全陌生,正在尝试构建一个非常简单的内容 slider ,该 slider 在某些 DIV 之间淡入淡出。每次过渡/淡入淡出的持续时间应取决于各个 DIV 中的字符数。
我当前的代码似乎是对字符进行计数并调整 setTimeout 函数,但它是针对下一个 div 执行此操作,而不是计算的那个 div。
任何帮助将不胜感激。
$(document).ready(function() {
var allBoxes = $("div.boxes").children("div");
transitionBox(null, allBoxes.first());
});
function transitionBox(from, to) {
function next() {
var nextTo;
// here i am getting the length of the div
var dur = $(this).text().length * 10;
if (to.is(":last-child")) {
nextTo = to.closest(".boxes").children("div").first();
} else {
nextTo = to.next();
}
to.fadeIn(500, function() {
setTimeout(function() {
transitionBox(to, nextTo);
// adding the length here delays the next slide, not the one i counted the characters in
}, dur);
});
}
if (from) {
from.fadeOut(500, next);
} else {
next();
}
}
.boxes div {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boxes">
<div class="box1">text1</div>
<div class="box2">text2</div>
<div class="box3">text3</div>
</div>
最佳答案
您的问题在以下行中:
var dur = $(this).text().length * 10;
这里不能使用$(this)
,而是使用to
变量,因为this
是一个窗口
你的情况下的对象。这是一篇关于 JavaScript 中 this
的好文章 http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
关于javascript - 根据字符数淡化 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35855696/