Выводим слова в данной области из массива
Добрый день уважаемые. Возник интерес реализовать такой эффект при помощи jQuery.
-Необходимо с периодичностью в 3сек генерировать в параграфы слова из массива, при этом каждое новое слово должно иметь свой цвет, свой размер и свое положение в пространстве окна браузера. Условия: 1) Слова на экране браузера появляются в случайное время, но их должно быть не больше 10 Если одно слово появляется ( допустим opaciti 0 -> 1), то другое исчезает ( допустим opaciti 1 -> 0) 2) Слова которые создаются не должны попадать в область расположения блока. ( С этим у меня проблемы, не знаю как придумать правило проверки) Блок будет плавающим в пространстве через margin ![]() Я начало кода набросал, а дальше меня застопорило. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <style type="text/css"> body{ position: relative; width: 100%; height: 100%; } .box{ width: 200px; height: 200px; border: 1px solid #000; margin: 10% auto; text-align: center; } .word{ position: absolute; top: 20%; left: 20%; /*animation: wordLife 3s linear ;*/ /* подключить*/ animation-fill-mode: forwards; } @keyframes wordLife { 0%{ opacity: 0; } 25%, 75%{ opacity: 1; } 100%{ opacity: 0; } } </style> </head> <body> <div class="box">block</div> <p class="word"></p> <script type="text/javascript"> window.onload = function () { var arr = ["Test0", "sddfsdf", "Test2dfdf", "Test3dd", "Test4df", "Test5fsdf", "Test6sdf",]; var len = arr.length - 1; var $box = $('.box'), boxW =$box.innerWidth(), boxH =$box.innerHeight(); var $txt = $('p'), txtW = $txt.innerWidth(), txtH = $txt.innerHeight(); var winW = $(window).width(), winH = $(window).height(); console.log(winW + " =w"); console.log(winH + " =h"); function randomInteger(min, max) { var rand = min - 0.5 + Math.random() * (max - min + 1) rand = Math.round(rand); return rand; }; var randNum = randomInteger(0, len), randTextSize = randomInteger(155, 400)/100, randR = randomInteger(0, 255), randG = randomInteger(0, 255), randB = randomInteger(0, 255), randTop = randomInteger(0, winH), radLeft = randomInteger(0, winW); console.log( randR+ " =randR "); console.log( randG+ " =randG "); console.log( randB+ " =randB "); console.log( randTextSize+ " =randTextSize "); function createWord(){ $txt.css({'fontSize' : randTextSize + 'em', 'color' : 'rgb( '+ randR + ',' + randG + ',' + randB +' )', 'top' : randTop, 'left' : radLeft }); $txt.text(arr[randNum]); }; setInterval(createWord, 200); } </script> </body> </html> Вопрос 1)Почему у меня не создается новая строчка через каждый промежуток времени setInterval(createWord, 200);? 2) Почему у меня текст выбрасывает фиг знает куда, хотя я задаю значение top в промежутке от 0 до размеров окна браузера? 3) Как сделать что б сгенерированный текст не попадал в область блока(ни одной буквой)? :write: Буду очень благодарен за пояснения |
|
Black_Star,
Цитата:
|
Цитата:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <style type="text/css"> body{ position: relative; width: 100%; height: 100%; } .box{ width: 200px; height: 200px; border: 1px solid #000; margin: 10% auto; text-align: center; } .word{ position: absolute; top: 20%; left: 20%; /*animation: wordLife 3s linear ;*/ /* подключить*/ animation-fill-mode: forwards; } @keyframes wordLife { 0%{ opacity: 0; } 25%, 75%{ opacity: 1; } 100%{ opacity: 0; } } </style> </head> <body> <div class="box">block</div> <p class="word"></p> <script type="text/javascript"> window.onload = function () { var arr = ["Test0", "sddfsdf", "Test2dfdf", "Test3dd", "Test4df", "Test5fsdf", "Test6sdf",]; var len = arr.length - 1; var $box = $('.box'), boxW =$box.innerWidth(), boxH =$box.innerHeight(); var $txt = $('p'), txtW = $txt.innerWidth(), txtH = $txt.innerHeight(); var winW = $(window).width(), winH = $(window).height(); console.log(winW + " =w"); console.log(winH + " =h"); function randomInteger(min, max) { var rand = min + Math.random() * (max - min + 1) rand = Math.round(rand); return rand; }; function createWord(){ var randNum = randomInteger(0, len), randTextSize = randomInteger(155, 400)/100, randR = randomInteger(0, 255), randG = randomInteger(0, 255), randB = randomInteger(0, 255), randTop = randomInteger(0, winH), radLeft = randomInteger(0, winW); console.log( randR+ " =randR "); console.log( randG+ " =randG "); console.log( randB+ " =randB "); console.log( randTextSize+ " =randTextSize "); $txt.clone().css({'fontSize' : randTextSize + 'em', 'color' : 'rgb( '+ randR + ',' + randG + ',' + randB +' )', 'top' : randTop, 'left' : radLeft }).text(arr[randNum]).appendTo('body'); }; setInterval(createWord, 200); } </script> </body> </html> |
рони,
Процесс пошел:) Но почему вы, а не Black_Star? (я про клоны специально промолчал, чтобы ТС подумал) |
Спасибо за подсказки. :thanks:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> <style type="text/css"> body{ position: relative; width: 100vw; height: 100vh; } .box{ width: 200px; height: 200px; border: 1px solid #000; position: absolute; top: calc(50% - 200px); left: calc(50% - 200px); text-align: center; } p{ display: block; margin: 0; padding: 0; width: 50px; height: 50px; } .word{ position: absolute; animation: wordLife 7s linear ; /* подключить*/ animation-fill-mode: forwards; } @keyframes wordLife { 0%{ opacity: 0; } 25%, 75%{ opacity: 1; } 100%{ opacity: 0; } } </style>> </head> <body> <div class="box">block</div> <p class="word"></p> <script type="text/javascript"> window.onload = function () { var arr = ["Test0", "Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10", "Test11", "Test12"]; var len = arr.length - 1; var $box = $('.box'), boxW =$box.innerWidth(), boxH =$box.innerHeight(); var $txt = $('p'), txtW = $txt.innerWidth(), txtH = $txt.innerHeight(), elements = 30; // сколько элементов я хочу что б показывало в окне браузера var winW = $(window).width(), winH = $(window).height(); function randomInteger(min, max) { var rand = min + Math.random() * (max - min + 1) rand = Math.round(rand); return rand; }; function createWord(){ var randNum = randomInteger(0, len), randTextSize = randomInteger(155, 400)/100, randR = randomInteger(0, 255), randG = randomInteger(0, 255), randB = randomInteger(0, 255), randTop = randomInteger(0, (winH - txtH)), radLeft = randomInteger(0, (winW - txtW)); var txtValue = $txt.clone().css({'fontSize' : randTextSize + 'em', 'color' : 'rgb( '+ randR + ',' + randG + ',' + randB +' )', 'top' : randTop, 'left' : radLeft }) txtValue.text(arr[randNum]).appendTo('body'); console.log( txtW + " = txtW "); console.log( txtH + " = txtH"); }; function limitWords () { if ($('p').length < elements) { createWord() } else{ $('p').first().remove(); } } setInterval(limitWords, 500); } </script> </body> </html> Осталось непонятными два вопроса. 1) Как ограничить поле вывода слов размером экрана браузера. ( randTop = randomInteger(0, (winH - txtH)) работает как-то не правильно) 2) Как сделать так что б слова не наплывали поверх блока. У ksa в примере как-то всё очень хитро записано, да и оно не совсем то что мне надо |
Цитата:
У меня в этой теме нет примеров... :no: |
ksa,
пост №2 |
Цитата:
Цитата:
Цитата:
- генерация цвета - случайное позиционирование в определенной области - проверка на пересечение Т.ч. достаточно много чего, что тебе пригодилось бы... ;) |
Black_Star,
Цитата:
Вы пытаетесь использовать txtH и txtW - но эти переменные у вас определяются один раз и соответствуют значениям, прописанным в стиле для p, тогда как реальные размеры каждого слова разные. И что в этой ситуации плохо - новые слова получают значения innerWidth() и innerHeight() после включения в DOM. Как выкручиваться - ??? |
Часовой пояс GMT +3, время: 21:04. |