Пунктуация загрузки "анимация", javascript?
Я ищу хороший способ отображения некоторой анимации "пунктуации".
Я хочу что-то вроде этого:
This will display at second 1: "Waiting for your input."
This will display at second 2: "Waiting for your input.."
This will display at second 3: "Waiting for your input..."
This will display at second 4: "Waiting for your input...."
This will display at second 5: "Waiting for your input."
This will display at second 6: "Waiting for your input.."
This will display at second 7: "Waiting for your input..."
This will display at second 8: "Waiting for your input...."
И так далее.
Я начал с окружающих точек в spans
и думал, что смогу их прокрутить с помощью jquery и отобразить еще один, еще один, еще один, затем reset до 1. Но код стал очень неуклюжим, поэтому я удивляюсь как вы это сделаете?
Ответы
Ответ 1
Трюк для создания строки точек состоит в том, чтобы сделать разреженный массив и затем соединить все элементы с нужным символом.
var count = 0;
setInterval(function(){
count++;
var dots = new Array(count % 10).join('.');
document.getElementById('loadingtext').innerHTML = "Waiting for your input." + dots;
}, 1000);
Вот демо-версия.
Ответ 2
Чистое решение для CSS
Демо: jsfiddle.net/feklee/D59P9
-
HTML:
Waiting<span class="dots"><span>.</span><span>.</span><span>.</span></span> for more.
-
CSS
@keyframes dots-1 { from { opacity: 0; } 25% { opacity: 1; } }
@keyframes dots-2 { from { opacity: 0; } 50% { opacity: 1; } }
@keyframes dots-3 { from { opacity: 0; } 75% { opacity: 1; } }
@-webkit-keyframes dots-1 { from { opacity: 0; } 25% { opacity: 1; } }
@-webkit-keyframes dots-2 { from { opacity: 0; } 50% { opacity: 1; } }
@-webkit-keyframes dots-3 { from { opacity: 0; } 75% { opacity: 1; } }
.dots span {
animation: dots-1 1s infinite steps(1);
-webkit-animation: dots-1 1s infinite steps(1);
}
.dots span:first-child + span {
animation-name: dots-2;
-webkit-animation-name: dots-2;
}
.dots span:first-child + span + span {
animation-name: dots-3;
-webkit-animation-name: dots-3;
}
Альтернатива только для WebKit
Преимущество: нет вложенных тегов. Это означает, что эллипсис можно разместить как контент
в псевдоэлемент ::after
.
Демо: jsfiddle.net/feklee/vFT7W
-
HTML:
Waiting<span>...</span> for more.
-
CSS
body {
font-family: 'Roboto', sans-serif;
font-size: 50px;
}
@-webkit-keyframes dots {
0% { background-position: 0px; }
100% { background-position: 50px; }
}
span {
background: linear-gradient(to right, white 50%, black 50%);
color: transparent;
-webkit-background-clip: text;
-webkit-animation: dots 1s infinite steps(4);
padding-right: 40px;
margin-right: -40px;
}
Ответ 3
Это может быть очень просто:
HTML
<span class="dots"></span>
JQuery
setInterval(function() {
var th = $('.dots');
if(th.text().length < 5){
th.text(th.text()+".");
}else{
th.text("");
}
}, 500);
Демо
Ответ 4
Теперь, как только код вышел из-под контроля, вы можете просто сделать:
setInterval(function () {
var span = $("#text-loader").children("span:eq(0)");
var ellipsis = span.html();
ellipsis = ellipsis + ".";
if (ellipsis.length > 5) {
ellipsis = ".";
}
span.html(ellipsis);
}, 1000);
<div id="text-loader">
This will display at second 1: "Waiting for your input<span>.</span>
</div>
А что касается 1
, вы можете поменять его на количество периодов.
Ответ 5
попробуйте эту функцию: здесь я приведу пример http://jsfiddle.net/XFd39/
var i=0;
function f() {
if(i<=4)
$('#a').append(".");
i++;
if(i==4){
$('#a').html("");
i=0;
}
setTimeout(f,500);
}
f();
Ответ 6
Вот довольно простой вариант: http://jsfiddle.net/psycketom/FusdC/
Прочитайте комментарии ниже, чтобы понять, что там делает.
var span = $('.dots'); // take the element where you have the maximum count of dots
var text = span.text(); // cahce it text value
// we set up a function here, so we can loop it all the time
var loading = function()
{
$({
count : 1 // we start at one dot
}).animate({
count : text.length // together forming all of it
}, {
duration : 1000, // make the animation complete in one second
step : function() {
span.text( text.substring(0, Math.round(this.count)) ); // on each step, change the text accordingly to current iteration
},
complete : function() {
loading(); // once complete, start all over again
}
});
};
loading(); // start it up for the first time
Здесь вы также можете воспользоваться easing
, если хотите, легко изменяя общую продолжительность и совокупность других преимуществ, если вы хорошо разбираетесь в jQuery.
Ответ 7
Чувак, если вы не хотите отображать эту анимацию навсегда, вам понадобится способ остановить анимацию или?
Даже не думайте о глобальных переменных, это JavaScript, и для этого было закрыто:)
<p>please wait<span id="wait"></span></p>
<input type="submit" id="start" value="start">
<input type="submit" id="stop" value="stop">
<script type="text/javascript">
$(document).ready(function() {
var animator = function($el) {
var dotCount = 1;
var started = true;
return {
"start" : function step() {
dotCount = (dotCount + 1) % 10;
$el.text(new Array(dotCount).join('.'));
if (started) {
setTimeout(step, 100);
}
},
"stop" : function() {
started = false;
}
}
};
var animatedWait = animator($("#wait"));
$("#start").click(animatedWait.start);
$("#stop").click(animatedWait.stop);
});
</script>