我是jQuery的新手,并尝试构建一个非常简单的内容滑块,在某些DIV之间淡出。每次转换/淡入淡出的持续时间应取决于各个DIV中的字符数量。
我当前的代码似乎会对字符进行计数并调整setTimeout函数,但它会对下一个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();
}
}
这是JSFiddle
上的所有内容答案 0 :(得分:1)
您的问题在以下一行:
var dur = $(this).text().length * 10;
您不能在此使用$(this)
,而是使用to
变量,因为this
是您案例中的window
对象。这是一篇关于JavaScript http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
this
的好文章