(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);
});
});
// найдем все элементы с классом 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
}
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);
})
您可以在关键字 随机字母效果下在google上搜索
或者你可以使用现成的jQuery 动画 Shuffle Letters Effect插件
或者您可以使用我在下面写的内容,并在此基础上写出您需要的内容的精确副本。
更新:让它看起来像在 gif 中。你仍然会感到困惑并制作完整的副本,但我把它留给你。
链接到这里的源代码
感谢大家。
像这样的东西:
一旦需要类似的功能,我就找到了这个脚本。如果你使用“现代 JS”,我认为你可以写得更短。