Текстовый эффект
Приветствую!
Недавно нашел такой скрипт, который создает эффект растягивания текста <script>var sizes = new Array("0px", "1px", "2px","4px", "8px"); sizes.pos = 0; function rubberBand() { var el = document.all.elastic; if (null == el.direction) el.direction = 1; else if ((sizes.pos > sizes.length - 2) || (0 == sizes.pos)) el.direction *= -1; el.style.letterSpacing = sizes[sizes.pos += el.direction]; } window.tm = setInterval('rubberBand()', 100); </script> <font color="#ffd700" id="elastic">Text Текст</font> Подскажите как сделать так, чтобы, например после второго сжатия эффект прекращался? |
<script>var sizes = new Array("0px", "1px", "2px","4px", "8px"); sizes.pos = 0; var count = 0; function rubberBand() { var el = document.all.elastic; if (sizes.pos === 0) count++; if (count > 2) { clearInterval(window.tm); count = 0; return; } if (null == el.direction) el.direction = 1; else if ((sizes.pos > sizes.length - 2) || (0 == sizes.pos)) el.direction *= -1; el.style.letterSpacing = sizes[sizes.pos += el.direction]; } window.tm = setInterval(rubberBand, 100); </script> <font color="#ffd700" id="elastic">Text Текст</font> |
jsnb,
Премного благодарен. Случайно не знаете как сделать так, чтобы текст помимо растягивания (letterSpacing) уменьшался и увеличивался в размере? |
Цитата:
|
jsnb,
Спасибо, сработало! |
Только вот еще не пойму, если добавить второй массив для fontSize, как ту быть?
var sizes2 = new Array("12px", "15px", "19px"); .... el.style.fontSize = sizes2[sizes2.pos += el.direction]; // не срабатывает |
Цитата:
el.style.fontSize = sizes2[sizes.pos += el.direction]; или отдельно считать счетчик позиций в функции для второго массива. |
jsnb, если делать столько же элементов, как в первом массиве, то не стоит ли тогда рассмотреть вариант, что бы первый массив сделать из мелких массивов или заменить массив на обьект ?
[[0, 12], [1, 15], [2, 19],[4, ?], [8, ?]] ? -- число px -- вынести в скрипт, где устанавливается значение, так... ну или, что бы было понятно читать, что к чему относится... [ {'size': 0,'fontSize':12}, {'size': 1,'fontSize':15}, {'size': 2,'fontSize':19}, {'size': 4,'fontSize':?}, {'size': 8,'fontSize':?} ] Предложил бы еще вот так, тогда будет проще перебирать... вот только помню, были какие то траблы, когда числа в качестве ключей... (поискал, надо ключи не в виде чисел представить, в противном случаи произойдет сортировка перед перебором) {0: 12, 1: 15, 2: 19 4: ?, 8: ?} превращается в {"0px": 12, "1px": 15, "2px": 19 "4px": ?, "8px": ?} В результате, ключ уже сразу вписывать, а вот при использовании значения, тогда дописывать "px", хотя можно и не заморачиваться с этим и сразу тогда писать с "px" |
Благодарю за ответы, очень помогли
|
А как вместо этого var el = document.all.elastic; подставить что-то на подобии $('div[id^="elastic"]'); .. ?
|
cript,
Ну если получить все id, которые начинаются на elastic, то $('[id^="elastic"]') А в вашем варианте, получить все div с id, которые начинались на elastic. Потому, смотря, что именно вы ходите получить... по коду выше, то там font в качестве тега, потому конструкция написанная вами не выдаст в результат... актуально описание всех api http://api.jquery.com/ если надо раша вариант, то немного не угоняющийся за актуальностью, но все же http://jquery.page2page.ru/tags/ifr.html найдите описание по работе с селекторами и смотрите) |
Делаю так var el = $('[id^="elastic"]') , но не срабатывает, да и так тоже var el = $('font[id^="elastic"]')
|
cript,
а что не срабатывает? var el = $('[id^="elastic"]'); //должен получить все, что найдет.... что у вас в el ? |
<script src="//code.internetrange.com/jquery-1.8.3.js"></script> <script> var sizes = new Array("16px", "18px", "20px", "22px", "23px"); sizes.pos = 0; var count = 0; function rubberBand(value) { var el = $('[id^="elastic"]'); if (sizes.pos === 0) count++; if (count > 2) { clearInterval(window.tm); count = 0; return; } if (null == el.direction) el.direction = 1; else if ((sizes.pos > sizes.length - 2) || (0 == sizes.pos)) el.direction *= -1; el.style.fontSize = sizes[sizes.pos += el.direction]; } window.tm = setInterval('rubberBand()', 100); </script> <font id="elastic">Text Текст</font> |
cript,
jquery тут как .... рукав ... скрипты не работают со сферическими конями ... поэтому ставим ниже элемента ... учим что такое готовность страницы. <font id="elastic">Text Текст</font> <script src="http://code.internetrange.com/jquery-1.8.3.js"></script> <script> var sizes = new Array("16px", "18px", "20px", "22px", "23px"); sizes.pos = 0; var count = 0; function rubberBand(value) { var el = $('[id^="elastic"]')[0]; if (sizes.pos === 0) count++; if (count > 2) { clearInterval(window.tm); count = 0; return; } if (null == el.direction) el.direction = 1; else if ((sizes.pos > sizes.length - 2) || (0 == sizes.pos)) el.direction *= -1; el.style.fontSize = sizes[sizes.pos += el.direction]; } window.tm = setInterval('rubberBand()', 100); </script> |
рони,
<font id="elastic2">Text Текст</font> <script src="http://code.internetrange.com/jquery-1.8.3.js"></script> <script> var sizes = new Array("16px", "18px", "20px", "22px", "23px"); sizes.pos = 0; var count = 0; function rubberBand(value) { var el = $('[id^="elastic"]'); if (sizes.pos === 0) count++; if (count > 2) { clearInterval(window.tm); count = 0; return; } if (null == el.direction) el.direction = 1; else if ((sizes.pos > sizes.length - 2) || (0 == sizes.pos)) el.direction *= -1; el.style.fontSize = sizes[sizes.pos += el.direction]; } window.tm = setInterval('rubberBand()', 100); </script> Почему так не срабатывает..? |
cript,
потому что el у вас обьект jquery у которого нет свойства style но есть ключик ноль там и лежит искомый элемент. смотрите пост выше - строка 9 |
Какой ужас :blink:
|
<div class="elastic">Текст</div> <div class="elastic">Еще один текст</div> <script> var k = 0; var npoz = next(); var allel = document.querySelectorAll("div.elastic"); var tm = setInterval(rubberBand, 100); function next() { var i = -1; return function () { i = i < 7 ? i + 1 : 0; return [16, 18, 20, 22, 23, 22, 20, 18][i]; }; } function rubberBand() { if (k == 16) clearInterval(tm); var fsize = npoz() + "px"; for (var j = 0; j < allel.length; j += 1) { allel[j].style.fontSize = fsize; } k += 1; } </script> |
имхо: через css проще правда в IE<10 не будет работать =)
<style type="text/css"> b {font-size: 14pt;} .ani{-webkit-animation: gogo 1s;-webkit-animation-iteration-count: 2; animation: gogo 1s;animation-iteration-count: 2;} @-webkit-keyframes gogo{ 0% {font-size: 14pt;color: #23ff00;} 100% {font-size: 24pt;color: #b70000;}} @keyframes gogo{0% {font-size: 14pt;color: #23ff00;}100% {font-size: 24pt;color: #b70000;}} </style> <script> setTimeout(" $('[id^=\"elastic\"]').addClass(\"ani\") ", 500); </script> <b id="elastic">Text Текст</b><br> <b id="no_elastic2">Text Текст</b><br> <b id="elastic2_asdf">Text Текст</b><br> <b id="no_elastic3">Text Текст</b><br> |
MallSerg, зачем вообще Jquery?
<style type="text/css"> b { font-size: 14pt } [id^="elastic"]{ -webkit-animation: gogo 1s; -webkit-animation-iteration- count: 2; animation: gogo 1s; animation-iteration-count: 2; } @-webkit-keyframes gogo{ 0% { font-size: 14pt } 50% { font-size: 24pt } } @keyframes gogo{ 0% { font-size: 14pt } 50% { font-size: 24pt } } </style> <b id="elastic">Text Текст</b><br> <b id="no_elastic2">Text Текст</b><br> <b id="elastic2_asdf">Text Текст</b><br> <b id="no_elastic3">Text Текст</b><br> P.S. Используйте [html run]...[/html] для наглядности. |
Aetae,
Не плохой вариант, пытаюсь сделать так, но ничего не происходит, скажите в чем тут ошибка? <script src="//code.internetrange.com/jquery-1.8.3.js"></script> <style> .elastic [id^="stat"] { -webkit-animation: elastic 1s; -webkit-animation-iteration- count: 2; animation: elastic 1s; animation-iteration-count: 2; } @-webkit-keyframes elastic { 0% { font-size: 14pt; } 50% { font-size: 24pt; } } @keyframes elastic { 0% { font-size: 14pt; } 50% { font-size: 24pt; } } </style> <script> $(document).ready(function() { $("#stat").addClass('elastic'); }); </script> <div id="stat">Text</div> <div id="stat2">Text2</div> |
Ошибка в том что в css нет класса который ты пытаешься добавить (.addClass('elastic');)
<script src="http://code.internetrange.com/jquery-1.8.3.js"></script> <style type="text/css"> .elastic { -webkit-animation: elastic 5s; -webkit-animation-iteration- count: 4; animation: elastic 5s; animation-iteration-count: 2;} @-webkit-keyframes elastic {0% {font-size: 14pt;}50%{font-size: 84pt;}} @keyframes elastic {0% {font-size: 14pt;}50% {font-size: 84pt;}} </style> <script> $(document).ready(function() { $("#stat").addClass('elastic');}); </script> <div id="stat">Text</div> <div id="stat2">Text2</div> |
Часовой пояс GMT +3, время: 05:26. |