Форум программистов, компьютерный форум, киберфорум
jQuery
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.94/34: Рейтинг темы: голосов - 34, средняя оценка - 4.94
 Аватар для cadabra
0 / 0 / 0
Регистрация: 24.12.2018
Сообщений: 17

Рандомное появление текста

27.12.2018, 00:44. Показов 6445. Ответов 4

Студворк — интернет-сервис помощи студентам
Здравствуйте. У меня есть скрипт, который анимирует смену текста.

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type="text/javascript">
    $(function() {
      var list = ['"Всякий путь, если только он ведет к нашим мечтам, есть путь магический." \n(Пауло Коэльо. Дневник мага)', '"Настоящая магия творится у людей в головах."\n(Терри Пратчетт)'
      ];
 
      var txt = $('#txtlzr');
 
      txt.textualizer(list, {
        centered: true
      });
      txt.textualizer('start');
    })
 
  </script>
Ниже код самого скрипта:
Кликните здесь для просмотра всего текста
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
(function($, window) {
 
  "use strict";
 
  var Textualizer,
 
    COMMON_CHARACTER_ARRANGE_DELAY = 1000,
    REMAINING_CHARACTERS_DELAY = 500,
    EFFECT_DURATION = 2000,
    REMAINING_CHARACTERS_APPEARANCE_MAX_DELAY = 2000,
    REMOVE_CHARACTERS_MAX_DELAY = 2000,
 
    EVENT_CHANGED = 'textualizer.changed';
 
  // Gets the computed style of an element
  function getStyle(element) {
 
    var computedStyle, key, camelCasedStyle, i, len, styleList = {};
 
    if (window.getComputedStyle) {
      computedStyle = window.getComputedStyle(element, null);
 
      if (computedStyle.length) {
        for (i = 0, len = computedStyle.length; i < len; i++) {
          camelCasedStyle = computedStyle[i].replace(/\-([a-z])/, function(a, b) {
            return b.toUpperCase();
          });
 
          styleList[camelCasedStyle] = computedStyle.getPropertyValue(computedStyle[i]);
        }
      } else {
        for (key in computedStyle) {
          if (typeof computedStyle[key] !== 'function' && key !== 'length') {
            styleList[key] = computedStyle[key];
          }
        }
      }
    } else {
      computedStyle = element.currentStyle || element.style;
 
      for (key in computedStyle) {
        if (Object.prototype.hasOwnProperty.call(computedStyle, key)) {
          styleList[key] = computedStyle[key];
        }
      }
    }
 
    return styleList;
  }
 
  function Character() {
    this.character = null; // A character
    this.domNode = null; // The span element that wraps around the character
    this.pos = null; // The domNode position
    this.used = false;
    this.inserted = false;
    this.visited = false;
  }
 
  function Snippet() {
    this.str = ''; // The text string
    this.characterList = []; // Array of ch objects
  }
 
  Snippet.prototype = {
    // Loops through <characterList>, and find the first character that matches <val>, and hasn't been already used.
    use: function(val) {
      var ch = null;
 
      $.each(this.characterList, function() {
        if (this.character === val && !this.used) {
          this.used = true;
          ch = this;
          return false; // break;
        }
      });
 
      return ch;
    },
    // Resets ever character in <characterList>
    reset: function() {
      $.each(this.characterList, function() {
        this.inserted = false;
        this.used = false;
      });
    }
  };
 
  Textualizer = function($element, data, options) {
    var self = this,
      list = [],
      snippets,
 
      index, previous, showCharEffect = null,
 
      playing = false,
      paused = false,
 
      elementHeight, position,
 
      $clone, $container, $phantomContainer;
 
    // If an effect is chosen, then look for it in the list of effects
    if (options.effect !== 'random') {
      $.each($.fn.textualizer.effects, function() {
        if (this[0] === options.effect) {
          showCharEffect = this[1];
          return false; // break;
        }
      });
    }
 
    // Clone the target element, and remove the id attribute (if it has one)
    // Why remove the id? Cuz when we clone an element, the id is also copied.  That's a very bad thing,
    $clone = $element.clone().removeAttr('id').appendTo(window.document.body);
 
    // Copy all the styles.  This is especially necessary if the clone was being styled by id in a stylesheet)
    $clone.css(getStyle($element[0]));
 
    // Note that the clone needs to be visible so we can do the proper calculation
    // of the position of every character.  Ergo, move the clone outside of the window's
    // visible area.
    $clone.css({
      position: 'absolute',
      top: '-1000px'
    });
 
    $phantomContainer = $('<div />').css({
      'position': 'relative',
      'visibility': 'hidden'
    }).appendTo($clone);
 
    // Make sure any animating character disappear when outside the boundaries of
    // the element
    $element.css('overflow', 'hidden');
 
    // Contains transitioning text
    $container = $('<div />').css('position', 'relative').appendTo($element);
 
    elementHeight = $element.height();
 
    position = {
      bottom: elementHeight
    };
 
    function positionSnippet(snippet, phantomSnippets) {
      // If options.centered is true, then we need to center the text.
      // This cannot be done solely with CSS, because of the absolutely positioned characters
      // within a relative container.  Ergo, to achieve a vertically-aligned look, do
      // the following simple math:
      var yOffset = options.centered ? (elementHeight - $phantomContainer.height()) / 2 : 0;
 
      // Figure out the positioning, and clone the character's domNode
      $.each(phantomSnippets, function(index, c) {
        c.pos = c.domNode.position();
        c.domNode = c.domNode.clone();
 
        c.pos.top += yOffset;
 
        c.domNode.css({
          'left': c.pos.left,
          'top': c.pos.top,
          'position': 'absolute'
        });
 
        snippet.characterList.push(c);
      });
 
      $phantomContainer.html('');
    }
 
    /* PRIVATE FUNCTIONS */
 
    // Add all chars first to the phantom container. Let the browser deal with the formatting.
    function addCharsToSnippet(i) {
      var phantomSnippets = [],
        snippet = new Snippet(),
        j, ch, c, len;
 
      snippet.str = list[i];
      snippets.push(snippet);
 
      for (j = 0, len = snippet.str.length; j < len; j++) {
        ch = snippet.str.charAt(j);
 
        if (ch === '') {
          $phantomContainer.append(' ');
        } else {
          c = new Character();
          c.character = ch;
          c.domNode = $('<span/>').text(ch);
 
          $phantomContainer.append(c.domNode);
          phantomSnippets.push(c);
        }
      }
 
      positionSnippet(snippet, phantomSnippets);
 
      return snippet;
    }
 
    function getHideEffect() {
      var dfd, eff;
 
      eff = [
 
        function(target) {
          dfd = $.Deferred();
          target.animate({
            top: position.bottom,
            opacity: 'hide'
          }, dfd.resolve);
          return dfd.promise();
        },
        function(target) {
          dfd = $.Deferred();
          target.fadeOut(1000, dfd.resolve);
          return dfd.promise();
        }
      ];
 
      return eff[Math.floor(Math.random() * eff.length)];
    }
 
    function removeCharacters(previousSnippet, currentSnippet) {
      var keepList = [],
        removeList = [],
        finalDfd = $.Deferred(),
        hideEffect = getHideEffect(),
        currChar;
 
      // For every character in the previous text, check if it exists in the current text.
      // YES ==> keep the character in the DOM
      // NO ==> remove the character from the DOM
      $.each(previousSnippet.characterList, function(index, prevChar) {
        currChar = currentSnippet.use(prevChar.character);
 
        if (currChar) {
          currChar.domNode = prevChar.domNode; // use the previous DOM domNode
          currChar.inserted = true;
 
          keepList.push(currChar);
        } else {
          (function hideCharacter(deferred) {
            removeList.push(deferred);
            hideEffect(prevChar.domNode.delay(Math.random() * REMOVE_CHARACTERS_MAX_DELAY)).done(function() {
              prevChar.domNode.remove();
              deferred.resolve();
            });
          })($.Deferred());
        }
      });
 
      $.when.apply(null, removeList).done(function() {
        return finalDfd.resolve(keepList);
      });
 
      return finalDfd.promise();
    }
 
    function showCharacters(snippet) {
      var effects = $.fn.textualizer.effects,
 
        effect = options.effect === 'random' ? effects[Math.floor(Math.random() * (effects.length - 2)) + 1][1] : showCharEffect,
 
        finalDfd = $.Deferred(),
        animationDfdList = [];
 
      // Iterate through all ch objects
      $.each(snippet.characterList, function(index, ch) {
        // If the character has not been already inserted, animate it, with a delay
        if (!ch.inserted) {
 
          ch.domNode.css({
            'left': ch.pos.left,
            'top': ch.pos.top
          });
 
          (function animateCharacter(deferred) {
            window.setTimeout(function() {
              effect({
                item: ch,
                container: $container,
                dfd: deferred
              });
            }, Math.random() * REMAINING_CHARACTERS_APPEARANCE_MAX_DELAY);
            animationDfdList.push(deferred);
          })($.Deferred());
 
        }
      });
 
      // When all characters have finished moving to their position, resolve the final promise
      $.when.apply(null, animationDfdList).done(function() {
        finalDfd.resolve();
      });
 
      return finalDfd.promise();
    }
 
    function moveAndShowRemainingCharacters(characters, currentSnippet) {
      var finalDfd = $.Deferred(),
        rearrangeDfdList = [];
 
      // Move charactes that are common to their new position
      window.setTimeout(function() {
        $.each(characters, function(index, item) {
 
          (function rearrangeCharacters(deferred) {
            item.domNode.animate({
              'left': item.pos.left,
              'top': item.pos.top
            }, options.rearrangeDuration, deferred.resolve);
            rearrangeDfdList.push(deferred.promise());
          })($.Deferred());
 
        });
        // When all the characters have moved to their new position, show the remaining characters
        $.when.apply(null, rearrangeDfdList).done(function() {
          window.setTimeout(function() {
            showCharacters(currentSnippet).done(function() {
              finalDfd.resolve();
            });
          }, REMAINING_CHARACTERS_DELAY);
        });
      }, COMMON_CHARACTER_ARRANGE_DELAY);
 
      return finalDfd.promise();
    }
 
    function rotater() {
      // If we've reached the last snippet
      if (index === list.length - 1) {
 
        // Reset the position of every character in every snippet
        $.each(snippets, function(j, snippet) {
          snippet.reset();
        });
        index = -1;
 
        // If loop=false, pause (i.e., pause at this last blurb)
        if (!options.loop) {
          self.pause();
        }
      }
 
      index++;
      next(index); // rotate the next snippet
    }
 
    function rotate(i) {
      var dfd = $.Deferred(),
        current = snippets[i];
 
      // If this is the first time the blurb is encountered, each character in the blurb is wrapped in
      // a span and appended to an invisible container, thus we're able to calculate the character's position
      if (!current) {
        current = addCharsToSnippet(i);
      }
 
      if (previous) {
        removeCharacters(previous, current).done(function(characters) {
          moveAndShowRemainingCharacters(characters, current).done(function() {
            dfd.resolve();
          });
        });
 
      } else {
        showCharacters(current).done(function() {
          dfd.resolve();
        });
      }
 
      previous = current;
 
      return dfd.promise();
    }
 
    function next(i) {
      if (paused) {
        return;
      }
 
      // <rotate> returns a promise, which completes when a blurb has finished animating.  When that
      // promise is fulfilled, transition to the next blurb.
      rotate(i).done(function() {
        $element.trigger(EVENT_CHANGED, {
          index: i
        });
        window.setTimeout(rotater, options.duration);
      });
    }
 
    /* PRIVILEDGED FUNCTIONS */
 
    this.data = function(dataSource) {
      this.stop();
      list = dataSource;
      snippets = [];
    };
 
    this.stop = function() {
      this.pause();
      playing = false;
      previous = null;
      index = 0;
      $container.empty();
      $phantomContainer.empty();
    };
 
    this.pause = function() {
      paused = true;
      playing = false;
    };
 
    this.start = function() {
      if (list.length === 0 || playing) {
        return;
      }
 
      index = index || 0;
      playing = true;
      paused = false;
 
      next(index);
    };
 
    this.destroy = function() {
      $container.parent().removeData('textualizer').end().remove();
 
      $phantomContainer.remove();
    };
 
    if (data && data instanceof Array) {
      this.data(data);
    }
  };
 
  $.fn.textualizer = function( /*args*/ ) {
    var args = arguments,
      snippets, options, instance, txtlzr;
 
    // Creates a textualizer instance (if it doesn't already exist)
    txtlzr = (function($element) {
 
      instance = $element.data('textualizer');
 
      if (!instance) {
        snippets = [];
 
        if (args.length === 1 && args[0] instanceof Array) {
          snippets = args[0];
        } else if (args.length === 1 && typeof args[0] === 'object') {
          options = args[0];
        } else if (args.length === 2) {
          snippets = args[0];
          options = args[1];
        }
 
        if (snippets.length === 0) {
          $element.find('p').each(function() {
            snippets.push($(this).text());
          });
        }
 
        // Clear the contents in the container, since this is where the blurbs will go
        $element.html("");
 
        // Create a textualizer instance, and store in the HTML node's metadata
        instance = new Textualizer($element, snippets, $.extend({}, $.fn.textualizer.defaults, options));
        $element.data('textualizer', instance);
      }
 
      return instance;
 
    })(this);
 
    if (typeof args[0] === 'string' && txtlzr[args[0]]) {
      txtlzr[args[0]].apply(txtlzr, Array.prototype.slice.call(args, 1));
    }
 
    return this;
  };
 
  $.fn.textualizer.defaults = {
    effect: 'random',
    duration: 10000,
    rearrangeDuration: 4000,
    centered: true,
    loop: true
  };
 
  // Effects for characters transition+animation. Customize as you please
  $.fn.textualizer.effects = [
    ['none', function(obj) {
      obj.container.append(obj.item.domNode.show());
    }],
    ['fadeIn', function(obj) {
      obj.container.append(obj.item.domNode.fadeIn(EFFECT_DURATION, obj.dfd.resolve));
      return obj.dfd.promise();
    }],
    ['slideLeft', function(obj) {
      obj.item.domNode.appendTo(obj.container).css({
        'left': -1000
      }).show().animate({
        'left': obj.item.pos.left
      }, EFFECT_DURATION, obj.dfd.resolve);
 
      return obj.dfd.promise();
    }],
    ['slideTop', function(obj) {
      obj.item.domNode.appendTo(obj.container).css({
        'top': -1000
      }).show().animate({
        'top': obj.item.pos.top
      }, EFFECT_DURATION, obj.dfd.resolve);
 
      return obj.dfd.promise();
    }]
  ];
 
})(jQuery, window);[JS]
[/JS]


1)Как можно сделать что бы текст появлялся в рандомных местах на экране?;
2) Как можно сделать что бы текст появлялся не по порядку, а рандомным образом?.
Заранее спасибо за предоставление любой информации.

Добавлено через 2 часа 26 минут
Цитата Сообщение от cadabra Посмотреть сообщение
2) Как можно сделать что бы текст появлялся не по порядку, а рандомным образом?.
Нашел скрипт один:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    <script type="text/javascript">
            window.addEvent('domready', function() {
                new Random({
                    container: $('random'),
                    typeNode: 'li',
                    speed: 5000,
                    duration: 700
                });
                new Random({
                    container: $('container'),
                    typeNode: 'div',
                    speed: 500,
                    duration: 700,
                    opacity: 0
                });
            });
 
        </script>
Но не могу понять что мне вставить в typeNode ?! Перепробовал куча вариантов. Скрипт не запускается у меня. И там еще есть значения времени и продолжительности. Мне это тоже не подходит, ведь в моем скрипте уже есть эти параметры. Возможно надо поискать другой вариант(скрипт)

Добавлено через 2 часа 34 минуты
Цитата Сообщение от cadabra Посмотреть сообщение
Нашел скрипт один:
Не подходит этот вариант
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
27.12.2018, 00:44
Ответы с готовыми решениями:

Рандомное перемещение текста
Суть задания в том что при нажатии на текст он перемещается в рандомное место, нужно обязательно использовать jquery. Я вот кое что...

Анимированное появление текста
Добрый день! Написал функцию которая получает текст и добавляет его в уже имеющийся список ul на первую позицию. Но для большей...

Постепеное появление текста
Мне нужно чтобы текст на сайте появлялся постепенно, как будто он печатается прямо сейчас. На java это выглядит как-то так: ...

4
566 / 465 / 183
Регистрация: 14.10.2017
Сообщений: 1,259
27.12.2018, 20:21
Лучший ответ Сообщение было отмечено cadabra как решение

Решение

HTML5
1
<div class="test"></div>
CSS
1
2
3
4
5
6
7
.test {
    max-width:180px;
    background: coral;
    z-index: 1;
    position:fixed;
    display: block;
}
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let popUpWindow = document.querySelector('.test');
let quotes = [
        '— Как тебя понимать?— Понимать меня необязательно. Обязательно любить и кормить вовремя.',
       'Всякий путь, если только он ведет к нашим мечтам, есть путь магический." \n(Пауло Коэльо. Дневник мага)',
       'Сначала казнь! Потом приговор!',
       'План, что и говорить, был превосходный: простой и ясный, лучше не придумать. Недостаток у него был только один: было совершенно неизвестно, как привести его в исполнение.',
       'Есть одно только благо — знание и одно только зло — невежество. Сократ',
       'Настоящая магия творится у людей в головах."\n(Терри Пратчетт)'
      ];
const showQuote = (el, txt) => {
    el.innerText = txt[Math.floor(Math.random() * txt.length)];
    el.style.left = Math.floor(Math.random() * (document.documentElement.clientWidth - el.offsetWidth)) + 'px';
    el.style.top = Math.floor(Math.random() * (document.documentElement.clientHeight - el.offsetHeight)) + 'px';
}
showQuote(popUpWindow, quotes);
1
 Аватар для cadabra
0 / 0 / 0
Регистрация: 24.12.2018
Сообщений: 17
29.12.2018, 00:45  [ТС]
Огромное спасибо. Этот метод прекрасно работает.
А можно как-то объединить мой скрипт с вашим. Я попробовал сделать вот так:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  $(function() {
      let popUpWindow = document.querySelector('.test');
      var list = [
        '— Как тебя понимать?— Понимать меня необязательно. Обязательно любить и кормить вовремя.',
        'Всякий путь, если только он ведет к нашим мечтам, есть путь магический." \n(Пауло Коэльо. Дневник мага)',
        'Сначала казнь! Потом приговор!',
        'План, что и говорить, был превосходный: простой и ясный, лучше не придумать. Недостаток у него был только один: было совершенно неизвестно, как привести его в исполнение.',
        'Есть одно только благо — знание и одно только зло — невежество. Сократ',
        'Настоящая магия творится у людей в головах."\n(Терри Пратчетт)'
      ];
      var txt = $('#txtlzr');
      txt.textualizer(list, {
        centered: true
      });
      txt.textualizer('start');
      const showQuote = (el, txt) => {
        el.innerText = txt[Math.floor(Math.random() * txt.length)];
        el.style.left = Math.floor(Math.random() * (document.documentElement.clientWidth - el.offsetWidth)) + 'px';
        el.style.top = Math.floor(Math.random() * (document.documentElement.clientHeight - el.offsetHeight)) + 'px';
      }
      showQuote(popUpWindow, list);
})
Но мой скрипт все равно не запускается.

Добавлено через 4 минуты
Цитата Сообщение от cadabra Посмотреть сообщение
Огромное спасибо. Этот метод прекрасно работает.
А можно как-то объединить мой скрипт с вашим. Я попробовал сделать вот так:
Я добавил класс тест вот сюда:
HTML5
1
2
3
4
5
6
7
  <body>
    <div id="container">
      <div id="txtlzr" class="test">
      </div>
    </div>
 
  </body>
Теперь на половину все заработало. А точнее запускается все, кроме самой анимации появления текста из первого скрипта. Пока не могу понять в чем проблема.

Добавлено через 2 минуты
Цитата Сообщение от cadabra Посмотреть сообщение
Теперь на половину все заработало. А точнее запускается все, кроме самой анимации появления текста из первого скрипта. Пока не могу понять в чем проблема.
Вот полный код:
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<!DOCTYPE html>
<html dir="ltr">
 
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="Ingredients/js/jquery.min.js"></script>
    <script src="Ingredients/js/textualizer.js"></script>
    <style media="screen">
      body {
 
      overflow: hidden;
      background-color: #1D1D1D;
 
    }
      .test {
        max-width: 180px;
        z-index: 1;
        position: fixed;
        display: block;
        color: rgba(102, 102, 102, 1);
      }
      #container {
 
        overflow: hidden;
        height: 100%;
        width: 100%;
        margin: 0 auto;
        text-align: center;
      }
 
      #txtlzr {
 
        font-size: 40px;
        width: 700px;
        margin: 0 auto;
        height: 700px;
        font-size: 40px;
        white-space: pre-wrap;
        color: rgba(102, 102, 102, 1);
      }
 
    </style>
  </head>
 
  <body>
    <div id="container">
      <div id="txtlzr" class="test">
      </div>
    </div>
 
  </body>
  <script type="text/javascript">
    $(function() {
      let popUpWindow = document.querySelector('.test');
      var list = [
        '— Как тебя понимать?— Понимать меня необязательно. Обязательно любить и кормить вовремя.',
        'Всякий путь, если только он ведет к нашим мечтам, есть путь магический." \n(Пауло Коэльо. Дневник мага)',
        'Сначала казнь! Потом приговор!',
        'План, что и говорить, был превосходный: простой и ясный, лучше не придумать. Недостаток у него был только один: было совершенно неизвестно, как привести его в исполнение.',
        'Есть одно только благо — знание и одно только зло — невежество. Сократ',
        'Настоящая магия творится у людей в головах."\n(Терри Пратчетт)'
      ];
      var txt = $('#txtlzr');
      txt.textualizer(list, {
        centered: true
      });
      txt.textualizer('start');
      const showQuote = (el, txt) => {
        el.innerText = txt[Math.floor(Math.random() * txt.length)];
        el.style.left = Math.floor(Math.random() * (document.documentElement.clientWidth - el.offsetWidth)) + 'px';
        el.style.top = Math.floor(Math.random() * (document.documentElement.clientHeight - el.offsetHeight)) + 'px';
      }
      showQuote(popUpWindow, list);
 
 
 
    })
 
  </script>
 
</html>
На стили не обращайте внимание, я потом отредактирую. Это все для теста.

Добавлено через 21 минуту
Все, разобрался.
Надо было
JavaScript
1
2
3
4
5
  var txt = $('#txtlzr');
      txt.textualizer(list, {
        centered: true
      });
      txt.textualizer('start');
добавить после:
JavaScript
1
showQuote(popUpWindow, list);
Добавлено через 6 минут
Цитата Сообщение от cadabra Посмотреть сообщение
Все, разобрался.
Надо было
Но теперь позиция текста меняется только 1 раз, после обновления страницы. Как вернуть эффект постоянной смены позиции?!

Добавлено через 3 часа 55 минут
Вообщем,
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script type="text/javascript">
    let popUpWindow = document.querySelector('#txtlzr');
    $(function() {
      let list = [
        '— Как тебя понимать?— Понимать меня необязательно. Обязательно любить и кормить вовремя.',
        'Всякий путь, если только он ведет к нашим мечтам, есть путь магический." \n(Пауло Коэльо. Дневник мага)',
        'Сначала казнь! Потом приговор!',
        'План, что и говорить, был превосходный: простой и ясный, лучше не придумать. Недостаток у него был только один: было совершенно неизвестно, как привести его в исполнение.',
        'Есть одно только благо — знание и одно только зло — невежество. Сократ',
        'Настоящая магия творится у людей в головах."\n(Терри Пратчетт)'
      ];
      const showQuote = (el, txt) => {
        el.innerText = txt[Math.floor(Math.random() * txt.length)];
        el.style.left = Math.floor(Math.random() * (document.documentElement.clientWidth - el.offsetWidth)) + 'px';
        el.style.top = Math.floor(Math.random() * (document.documentElement.clientHeight - el.offsetHeight)) + 'px';
      }
      showQuote(popUpWindow, list);
      var txt = $('#txtlzr');
      txt.textualizer(list, {
        centered: true
      });
      txt.textualizer('start');
 
    })
 
  </script>
Я где-то что-то напутал когда объединил оба скрипта.
Появление в рандомных местах (пока что только после обновления окна) работает, а вот появление цитат рандомным образом не работает, хотя должно.
Возможно, я где-то тут совершил ошибку:
JavaScript
1
2
3
4
5
6
showQuote(popUpWindow, list);
    var txt = $('#txtlzr');
    txt.textualizer(list, {
      centered: true
    });
    txt.textualizer('start');
Но пока не могу понять где именно.
0
566 / 465 / 183
Регистрация: 14.10.2017
Сообщений: 1,259
29.12.2018, 07:20
Лучший ответ Сообщение было отмечено cadabra как решение

Решение

похоже,вы используете плагин textualizer, я с ним не работал и вникать нет желания.
Если на чистом JS, чтобы окно всплывало через определенный промежуток времени:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const showQuote = el => {
    let txt = [
        '— Как тебя понимать?— Понимать меня необязательно. Обязательно любить и кормить вовремя.',
       'Всякий путь, если только он ведет к нашим мечтам, есть путь магический." \n(Пауло Коэльо. Дневник мага)',
       'Сначала казнь! Потом приговор!',
       'План, что и говорить, был превосходный: простой и ясный, лучше не придумать. Недостаток у него был только один: было совершенно неизвестно, как привести его в исполнение.',
       'Есть одно только благо — знание и одно только зло — невежество. Сократ',
       'Настоящая магия творится у людей в головах."\n(Терри Пратчетт)'
      ];
    el.innerText = txt[Math.floor(Math.random() * txt.length)];
    el.style.left = Math.floor(Math.random() * (document.documentElement.clientWidth - el.offsetWidth)) + 'px';
    el.style.top = Math.floor(Math.random() * (document.documentElement.clientHeight - el.offsetHeight)) + 'px';
}
let timerID = setInterval(() => showQuote(popUpWindow), 3 * 1000);//аргумент 3 * 1000 устанавливает интервал времени, сейчас 3 сек, меняем 3 на 5, будет 5 сек и т.д.
не надо этот скрипт всовывать ни в какие другие функции, просто добавьте его в самый низ своего скрипта
1
 Аватар для cadabra
0 / 0 / 0
Регистрация: 24.12.2018
Сообщений: 17
29.12.2018, 20:11  [ТС]
Цитата Сообщение от klopp Посмотреть сообщение
похоже,вы используете плагин textualizer, я с ним не работал и вникать нет желания.
Если на чистом JS, чтобы окно всплывало через определенный промежуток времени:
Большое спасибо за помощь.Вы очень помогли.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
29.12.2018, 20:11
Помогаю со студенческими работами здесь

Плавное появление/исчезновение текста
Добрый вечер. Помогите, плз, сделать такой эффект. Когда поле ввода получает фокус, где-то рядом появляется подсказка. Когда фокус...

Построковое появление текста в блоке
Суть такова: Есть блок который должен появится первый(затемнение и первая строка),в нем должен появляться построково текст(вторая...

Появление блока ввода текста при нажатии на ссылку
Помогите в написании скрипта, чтобы при нажатии на ссылку (не кнопка!) появился блок для ввода текста.

Рандомное появление swf
Сам не являюсь программистом js, поэтому прошу помощи в организации рандомного появяления flash роликов на сайте. Нужен простой и...

Появление текста
Можно ли сделать чтобы после нажатия на кнопку по буквам появлялся текст(код), а рядом с кодом крутилась картинка, типо загрузка, а после...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru