javascript - 根据字符数淡化 DIV

标签 javascript jquery html slider

我对 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/

相关文章:

html - W3C 验证程序错误 : Parse Error opacity=60

javascript - 子元素不拉伸(stretch)固定高度的父容器

javascript - 如何使用条件导入编写在浏览器和 Node 中都可以使用的 ESM 模块

javascript - Jquery 将文本框恢复为其原始值

javascript - JSON 数据网格就像 jQuery 中的 Excel

javascript - 如何在javascript中设置传递的函数

html - 如何在contenteditable区域编辑文本前后添加空格

javascript - Amazon Cognito - 需要电话验证 - 但不需要 MFA。有可能吗?

javascript - 这个简单的 chrome 扩展有什么问题?

Javascript/jQuery - 具有多个字段的时区更改脚本