首页 > 解决方案 > 使用间隔(和超时?)Javascript,JQuery 为文本设置动画

问题描述

我想让 Text 在循环中从左到右运行。这是我尝试的小提琴: https ://jsfiddle.net/9Lruxym8/33/

我从 css @keyframes 开始,但我认为如果我希望文本无缝运行,我需要文本本身的宽度。我的想法是写下文本两次,一旦带有文本的 div 运行到一半,动画就会重新开始。

@keyframes 不起作用后,我尝试了 jQuery 动画。它确实工作了一些,但运行并不顺利。现在我想通过过渡来做到这一点。我认为间隔和超时的组合可以解决问题,但我仍然无法正常工作 - 现在,我不知道为什么。有人对我有帮助吗?

function runText() {
  var text_width = $('#runningP').width()/2;
  console.log(text_width)

  setInterval(function(){
    console.log("interval");
    $('.text').css({'transition':'margin-left 5s'});
    $('.text').css({'margin-left':'-' + text_width + 'px'});
    moveBack();
  }, 3000);

  function moveBack() {
    console.log("timeout")
    setTimeout(function(){
      $('.text').css({'transition':'none'});
      $('.text').css({'margin-left': 0});
    }, 3000);
  }
}

runText();

标签: javascriptjquerysettimeoutsetinterval

解决方案


我最近为此功能编写了一些自定义代码。

查看我的代码,基本上有 3 个“级别”似乎有点多,(.scrollTextWrap > .scrollingText > .scrollContent)但这是我最终用来获得干净一致效果的结构。

我也添加了一个初始化程序,以便您可以简单地添加scrollMe类并让他们为您设置 html

在片段中,我添加了一个.parentContainer纯粹是为了展示它在受约束时是如何工作的

$(document)
    .ready(function(){
        // check that scrollingText has 2 scrollContent element
        $('.scrollMe')
            .each(function(){
                initScrollingText($(this));
            });
    });
    
function initScrollingText($this){
    // store text
    var text = $this.text();
    
    // empty element
    $this.html(null);
    
    var $wrap = $('<div class="scrollTextWrap" />'),
        $text = $('<div class="scrollingText" />'),
        $content = $('<div class="scrollContent" />');
    
    // set content value
    $content.text(text);
    
    // duplicate content
    $text
        .append($content)
        .append($content.clone());
        
    // append text to wrap
    $wrap.append($text)
    
    // add $wrap to DOM
    $wrap.insertAfter($this);
    
    // remove old element
    $this.remove();
}
/* to simulate width constraints */
.parentContainer {
    width: 140px;
    position:relative;
    overflow:hidden;
}

.scrollTextWrap {
    position:relative;
    width:auto;
    display:inline-block;
}

.scrollingText {
    display: flex;
    position:relative;
    transition:left 0.1s;
    animation: scrollText 5s infinite linear;
}

.scrollContent {
    white-space: nowrap;
    padding-right:5px;
}

@keyframes scrollText {
    0% { left:0 }
    100% { left:-50% }
}
<div class="parentContainer">
    <div class="scrollMe">Content you want to scroll goes here</div>
    <!-- alternatively you can just structure the html -->
    <div class="scrollTextWrap">
        <div class="scrollingText">
            <div class="scrollContent">Content you want to scroll goes here</div>
            <div class="scrollContent">Content you want to scroll goes here</div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读