11

Я новичок в web. Подскажите как написать скрипт для реализации такого эффекта"Эффект перебора символов

1
  • 1
    данный вопрос в виде картинки следует закрыть, потому что он бесполезен для базы знаний (тот, у кого возникнет подобный вопрос, не сможет найти данный вопрос и ответы к нему) 23 дек 2019 в 0:52

3 ответа 3

17

Можно искать в google под ключевым словом shuffle letter effect

Или можно использовать готовый плагин jQuery animation Shuffle Letters Effect

Либо можно использовать то что я написал снизу и на основе этого написать точную копию того что вам нужно.

Upd:Сделал еще похоже на то что в гифке.Можно еще заморочиться и сделать полную копию но это я оставляю вам.

Ссылка на исходный код тут

Спасибо всем.

(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>

4
  • неплохо было бы дать ссылку на источник 16 дек 2019 в 21:04
  • 1
    @Alexandr_TT если найду источник, то добавлю обязательно.Спасибо
    – Randall
    17 дек 2019 в 5:56
  • @Alexandr_TT обновил.
    – Randall
    17 дек 2019 в 8:00
  • 1
    Благодарю! Будет полезно в комплексе посмотреть всё и взять на вооружение :) 17 дек 2019 в 8:04
12

Как-то так:

// найдем все элементы с классом 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>

2
  • Чем не понятней, тем больше будет плюсов. и от меня (+) Пару строчек, хотя бы комментарий к коду. 16 дек 2019 в 21:03
  • 1
    @Alexandr_TT вроде написал... 16 дек 2019 в 21:13
2

Когда-то была необходимость в похожем функционале, нашел вот такой скрипт. Думаю, можно и короче написать, если использовать "современный 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>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.