RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1059312
Accepted
ref21
ref21
Asked:2020-12-16 19:28:03 +0000 UTC2020-12-16 19:28:03 +0000 UTC 2020-12-16 19:28:03 +0000 UTC

如何在 GIF 上实现这样的蛮力效果?

  • 772

我是网络新手。请告诉我如何写一个脚本来实现这个效果"迭代角色效果

javascript
  • 3 3 个回答
  • 10 Views

3 个回答

  • Voted
  1. Randall
    2020-12-16T20:16:57Z2020-12-16T20:16:57Z

    您可以在关键字 随机字母效果下在google上搜索

    或者你可以使用现成的jQuery 动画 Shuffle Letters Effect插件

    或者您可以使用我在下面写的内容,并在此基础上写出您需要的内容的精确副本。

    更新:让它看起来像在 gif 中。你仍然会感到困惑并制作完整的副本,但我把它留给你。

    链接到这里的源代码

    感谢大家。

    (function($) {
    
      $.fn.shuffleLetters = function(prop) {
    
        var options = $.extend({
          "step": 8, // How many times should the letters be changed
          "fps": 25, // Frames Per Second
          "text": "", // Use this text instead of the contents
          "callback": function() {} // Run once the animation is complete
        }, prop)
    
        return this.each(function() {
          var el = $(this),
            str = "";
    
          // Preventing parallel animations using a flag;
          if (el.data('animated')) {
            return true;
          }
          el.data('animated', true);
    
          if (options.text) {
            str = options.text.split('');
          } else {
            str = el.text().split('');
          }
    
          // The types array holds the type for each character;
          // Letters holds the positions of non-space characters;
    
          var types = [],
            letters = [];
    
          // Looping through all the chars of the string
    
          for (var i = 0; i < str.length; i++) {
    
            var ch = str[i];
    
            if (ch == " ") {
              types[i] = "space";
              continue;
            } else if (/[a-z]/.test(ch)) {
              types[i] = "lowerLetter";
            } else if (/[A-Z]/.test(ch)) {
              types[i] = "upperLetter";
            } else {
              types[i] = "symbol";
            }
    
            letters.push(i);
          }
    
          el.html("");
    
          // Self executing named function expression:
    
          (function shuffle(start) {
    
            // This code is run options.fps times per second
            // and updates the contents of the page element
    
            var i,
              len = letters.length,
              strCopy = str.slice(0); // Fresh copy of the string
    
            if (start > len) {
    
              // The animation is complete. Updating the
              // flag and triggering the callback;
    
              el.data('animated', false);
              options.callback(el);
              return;
            }
    
            // All the work gets done here
            for (i = Math.max(start, 0); i < len; i++) {
    
              // The start argument and options.step limit
              // the characters we will be working on at once
    
              if (i < start + options.step) {
                // Generate a random character at thsi position
                strCopy[letters[i]] = randomChar(types[letters[i]]);
              } else {
                strCopy[letters[i]] = "";
              }
            }
    
            el.text(strCopy.join(""));
    
            setTimeout(function() {
    
              shuffle(start + 1);
    
            }, 1000 / options.fps);
    
          })(-options.step);
    
    
        });
      };
    
      function randomChar(type) {
        var pool = "";
    
        if (type == "lowerLetter") {
          pool = "abcdefghijklmnopqrstuvwxyz0123456789";
        } else if (type == "upperLetter") {
          pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        } else if (type == "symbol") {
          pool = ",.?/\\(^)![]{}*&^%$#'\"";
        }
    
        var arr = pool.split('');
        return arr[Math.floor(Math.random() * arr.length)];
      }
    
    })(jQuery);
    
    
    $(function() {
      const el = $(".dummy");
      
      $.each( el, function( key, value ) {
        el.shuffleLetters();
    
        function shuffle(text) {
            el.shuffleLetters({text: text});
        };
         
        const arr = ['Первый скучный текст', 'текст углеродный :D', 'мифический текст', 'бессмертный текст'];
        let i = 0;
        const interval = setInterval(_ => shuffle(arr[i++ % arr.length]), 4000);
      });
    });
    html, body {
       margin:0;
       padding:0;
    }
    
    .main {
       background: #0f0c29;  /* fallback for old browsers */
        background: -webkit-linear-gradient(to right, #24243e, #302b63, #0f0c29);  /* Chrome 10-25, Safari 5.1-6 */
        background: linear-gradient(to right, #24243e, #302b63, #0f0c29); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
        display:-webkit-box;
        display:-webkit-flex;
        display:-moz-box;
        display:-ms-flexbox;
        display:flex;
    }
    .group {
        width:33%;
        color:#fff;
        font-family: 'Montserrat', sans-serif;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,500,700&display=swap" rel="stylesheet">
    
    
    <div class="main">
      <div class="group">
        <h3 class="dummy">Сейчас все будет терпение</h3>
        <small class="dummy">Тупой текст</small>
      </div>
      <div class="group">
        <h3 class="dummy">10 / 5</h3>
        <small class="dummy">millions</small>
      </div>
      <div class="group">
        <h3 class="dummy">Top 10</h3>
        <small class="dummy">Top credit card companies</small>
      </div>
    </div>

    • 18
  2. Best Answer
    Stranger in the Q
    2020-12-16T20:42:28Z2020-12-16T20:42:28Z

    像这样的东西:

    // найдем все элементы с классом shuffle
    let elements = document.querySelectorAll('.shuffle');
    // запомним текст в data-атрибут
    elements.forEach(el => el.dataset.text = el.textContent);
    // найдем время окончания анимации
    let maxTime = Math.max(...[...elements].map(e => 
          e.dataset.text.length * (e.dataset.delay || 200)));
    // запустим анимацию
    requestAnimationFrame(shuffle);
    
    function shuffle(t) {
      // если анимация еще не закончилась - запрашиваем еще кадр
      t < maxTime && requestAnimationFrame(shuffle);
      // перебор элементов
      elements.forEach(el => {
      
        if (t - el.dataset.t < (+el.dataset.speed || 50)) 
          return // если не настало время смены символов - выходим
        el.dataset.t = t; // запомним время
        let n = t/(+el.dataset.delay || 200) // индекс 
        let c = +el.dataset.count || 2; // число анимируемых символов
        
        // устанавливаем текст элементу: бьем строку посимвольно
        el.innerHTML = el.dataset.text.split('').map((s, i) => {   
          // выбираем случайные символы для необходимых позиций
          return i < n ? s : i-c > n ? '' : 
                String.fromCharCode(parseInt(Math.random()*95 + 32)); 
        }).join(''); // собираем обратно в строку
      });
    }
    body {
      background: linear-gradient(to left, steelblue, #111);
      color: white
    }
    <h1 class="shuffle" data-delay=400 data-speed=25 data-count=3>example text</h1>
    <span class="shuffle" data-delay=200 data-speed=50 data-count=5>one more text</span>

    • 12
  3. NeedHate
    2020-12-17T17:25:30Z2020-12-17T17:25:30Z

    一旦需要类似的功能,我就找到了这个脚本。如果你使用“现代 JS”,我认为你可以写得更短。

    var text_block = document.getElementById('Text_block').innerText; 
    var wrapper = document.getElementById('Wrapper');
    
    function getRandomCharacter(length){
        var possible =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        possible +=     "abcdefghijklmnopqrstuvwxyz";
        possible +=     "0123456789";
    
        if(length == null)
            return possible.charAt(Math.floor(Math.random() * possible.length));
        else{
            var text = "";
            for(var i = 0; i < length; i ++)
                text += getRandomCharacter();
    
            return text;
        }
    }
    
    function compare(source, target){
        var differences = []; 
        
        differences.push(target.length);
      
        for(var i = 0; i < Math.max(source.length, target.length); i ++){
            if(source.charAt(i) != target.charAt(i))
                differences.push(i);
        }
        return differences;
    }
    
    function iterateText(current, exclude){
        var text = "";
    
        for(var i=0; i < current.length; i++ ){
            // The character at position i is the same as target
            if($.inArray(i, exclude) == -1)
                text += current.charAt(i);
            // Iterate further with a new random character
            else
                text += getRandomCharacter();
        }
    
        // Add character if target string longer
        if(exclude[0] > current.length)
            text += getRandomCharacter();
        
        // Or remove character if target string shorter
        if(exclude[0] < current.length)
            text = text.substr(0, text.length-1);    
        return text;
    }
    
    function randomizeText (target, message, result, interval) {    
        // Compare the current string with the target string
        var diff = compare(message, result);
    
        // Shorten the timeout as the differences get smaller
        var acc = Math.max(interval * diff.length / result.length, 100);
        // clamp the slowest animation
        acc = Math.min(acc, 10);
    
        // Exit where no more differences found
        if(diff.length == 1)
            return;
    
        // Generate the next iteration of the text
        message = iterateText(message, diff);
    
        // Update the target label
        $(target).text(message);
        
        // Recursivelly call another iteration
        setTimeout(function () { randomizeText(target, message, result, interval); }, acc); 
    }
    
    function goFullRandom(){
      var text = text_block;
    
      randomizeText("#Text_block", getRandomCharacter(text.length), text, 1);
    }
    
    function onHover(element, force) {
        if(element.alreadyHovered == null || force) {
            goFullRandom();
          element.alreadyHovered = true;
        }
    }
    
    wrapper.addEventListener('mouseenter', function(){
    	onHover(this, true);
    })
    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro:300,400,700&subset=latin-ext'); 
    * {
    	box-sizing: border-box;
    }
    body {
    	background: #f2f2f2;
    	font-family: 'Source Code Pro', monospace;
    }
    .wrapper{
    	width: 300px; height: 300px;
    	margin: 30px auto;
    	background-color: #fff; 
    	box-shadow: 10px 10px 60px -20px rgba(0,0,0,.3);
    	display: flex; align-items: center; justify-content: center;
    	cursor: pointer;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="Wrapper" class="wrapper">
    	<div id="Text_block" class="text-block">
    		procrastinate
    	</div>
    </div>

    • 2

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5