css 字母的摇摆效果

dfty9e19  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(121)
jQuery(function ($) {
  var target = $("#target");
  target.html(target.text().replace(/./g, "<span>$&</span>"));

  setTimeout(runAnimation, 250);

  function runAnimation() {
    var index, spans;

    index = 0;
    spans = target.children();
    doOne();

    function doOne() {
      var span = $(spans[index]);
      if (!$.trim(span.text())) {
        // Skip blanks
        next();
        return;
      }

      // Do this one
      span.css({
          position: "relative",
        })
        .animate(
          {
            top: "-20",
          },
          "fast"
        )
        .animate(
          {
            top: "0",
          },
          "fast",
          function () {
            span.css("position", "");
            next();
          }
        );
    }

    function next() {
      ++index;
      if (index < spans.length) {
        doOne();
      } else {
        setTimeout(runAnimation, 500);
      }
    }
  }
 });
.title {
    margin: auto;
    width: 50%;
    color: black;
    text-align: right;
    
}

#target:hover {
    color: rgb(21, 121, 252);
    animation-name: bounce;
    animation-duration: 2s;
}

@keyframes bounce {
  0%   { transform: translateY(0); }
  50%  { transform: translateY(-50px); }
  100% { transform: translateY(0); }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="title">
        <p style="font-size: 45px;"><span id="target">I</span><span id="target">'</span><span id="target">m</span><span>
            </span><span id="target">K</span><span id="target">r</span><span id="target">i</span><span id="target">s</span>
        </p>
    </div>

我试图添加一个摆动效果的每一个字母,但我不能让它工作,我希望字母得到有点大,而悬停他们,使效果运行。我只是学习javascript,所以我不是真的很擅长它,片段不工作,我不知道是什么问题。我发现这个代码的摆动效果,但它不工作,有人能帮助吗?谢谢

ldfqzlk8

ldfqzlk81#

不要在单个span块中手动输入字母,而是让JavaScript来完成,这将更加灵活。
除此之外,你不需要用JavaScript来做动画,用CSS来做,这样会更简单,更容易处理。

const animatedElements = document.getElementsByClassName('animate');

[...animatedElements].forEach(elm => {
  let text = elm.innerText.split(''); // Split the text into letters and store them in an array
  
  elm.innerText = ''; // Clear the text in the div
  
  // Add the letters one by one, this time inside a <span>
  text.forEach(letter => {
    const span = document.createElement('span');
    span.innerText = letter;
    elm.appendChild(span);
  })
})
.animate>span {
  display: inline-block; /* Changing display from the default `inline` to `inline-block` so that `transform` rules apply */
  white-space: break-spaces; /* This is necessary so that the `inline-block` does not collapse the "spaces" */
  transition: transform 200ms ease-in-out;
}

.animate>span:hover {
  transform: translateY(-10px);
}

/* The following rules are just to format the embedded result */
.animate {
  margin: 40px;
  font-size: 40px;
}
<div class="animate">
  I'm Kris
</div>

相关问题