Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 17.07.2020, 13:31
Кандидат Javascript-наук
Отправить личное сообщение для Lefseq Посмотреть профиль Найти все сообщения от Lefseq
 
Регистрация: 19.04.2019
Сообщений: 124

Как сделать, чтобы блоки появлялись вместо уже существующих?
Здравствуйте. Помогите немного доработать код. Есть код, который рандомно выдает div блоки, которые появляются на пустом месте. Мне нужно сделать, чтобы блоки появлялись не на пустом месте, а заменяли уже находящиеся там другие блоки в которых были прописаны цифры.

<div class="box-container clearfix">
  <div><p>F</p></div>
  <div><p>a</p></div>
  <div><p>d</p></div>
  <div><p>e</p></div>
  <div><p>i</p></div>
  <div><p>n</p></div>
  <div><p>I</p></div>
  <div><p>m</p></div>
  <div><p>g</p></div>
</div>
 
 
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>


(function (factory) {
  if(typeof module === 'object' && typeof module.exports === 'object') {
    factory(require('jquery'), window, document);
  } else {
    factory(jQuery, window, document);
  }
}(function($, window, document, undefined) {
 
/**
 * @function external:"jQuery.fn".randomFadeIn
 * @arg {null|string|number} [duration='slow'] - Duration. Same to jQuery ".fadeIn()"
 * @arg {boolean} [isLoop=true] - Whether to repeat
 * @return {Object} jQuery object
 */
$.fn.randomFadeIn = function (duration, isLoop) {
  return this.each(function() {
    new $.randomFadeIn(this, duration, isLoop);
  });
};
 
/**
 * @class external:jQuery.randomFadeIn
 * @arg {Object} elem - An element to apply this plugin
 * @arg {null|string|number} duration - Duration. Same to jQuery ".fadeIn()"
 * @arg {boolean} isLoop - Whether to repeat
 * @prop {Object} elemChildren - Children of an element to apply this plugin
 * @prop {string|number} duration - Duration. Same to jQuery ".fadeIn()"
 * @prop {boolean} isLoop - Whether to repeat
 * @prop {Array} order - An array that contains indexes of elements to be shuffled
 */
$.randomFadeIn = function(elem, duration, isLoop) {
  this.elemChildren = $(elem).children();
  $(this.elemChildren).children().stop(true, false).hide();
  this.duration = duration || 'slow';
  this.isLoop = (isLoop === undefined) ? true : isLoop;
 
  // Create an array that contains order
  this.order = [];
  for (var i = 0, len = $(this.elemChildren).length; i < len; i++) {
    this.order[i] = i;
  }
 
  this.order = this._shuffleOrder(this.order);
  this._fadeInEach(0);
};
 
$.extend($.randomFadeIn.prototype, /** @lends external:jQuery.randomFadeIn.prototype */ {
  /**
   * Shuffle the array of elements
   * 
   * @private
   * @arg {Array}  order - An array that contains indexes of elements to be shuffled
   * @return {Array} An shuffled array
   */
  _shuffleOrder: function(order) {
    var idxLast = order.length;
    while (idxLast > 0) {
      var idxRandom = Math.floor(Math.random() * idxLast);
      idxLast--;
      var elemLast = order[idxLast];
 
      // Exchange each other
      order[idxLast]   = order[idxRandom];
      order[idxRandom] = elemLast;
    }
    return order;
  },
 
  /**
   * Run fade-in
   * 
   * @private
   * @arg {number} idx - An index of element to be fade-in
   */
  _fadeInEach: function(idx) {
    var len = $(this.elemChildren).length;
    var self = this;
    $(this.elemChildren).eq(this.order[idx]).children().fadeIn(
      this.duration,
      function() {
        idx++;
        if (idx < len) {
          // Run recursively until all elements fade in
          self._fadeInEach(idx);
        } else if (self.isLoop) {
          // Repeat fadeIn
          $(self.elemChildren).children().fadeOut(self.duration);
          self.order = self._shuffleOrder(self.order);
          self._fadeInEach(0);
        }
      }
    );
  }
}); // end of $.extend
 
}));
 
 
 
$(function() {
  $('.box-container').randomFadeIn();
});


.box-container {
  width: 232px;
}
 
.box-container div {
  float: left;
  height: 50px;
  margin-bottom: 8px;
  margin-right: 8px;
  overflow: hidden;
  width: 50px;
}
 
.box-container div p {
  background: #097;
  box-sizing: border-box;
  color: #fff;
  display: none;
  font-size: 20px;
  height: 100%;
  margin: 0;
  padding-top: 14px;
  text-align: center;
  width: 100%;
}
 
.clearfix:after {
  clear: both;
  content: '';
  display: block;
}
Ответить с цитированием
  #2 (permalink)  
Старый 17.07.2020, 14:06
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,134

Lefseq,
Ответить с цитированием
  #3 (permalink)  
Старый 17.07.2020, 14:38
Кандидат Javascript-наук
Отправить личное сообщение для Lefseq Посмотреть профиль Найти все сообщения от Lefseq
 
Регистрация: 19.04.2019
Сообщений: 124

рони,
?
Ответить с цитированием
  #4 (permalink)  
Старый 17.07.2020, 15:05
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,134

Lefseq,
попробуйте максимально просто описать, то что вы хотите сделать.
Ответить с цитированием
  #5 (permalink)  
Старый 17.07.2020, 15:35
Кандидат Javascript-наук
Отправить личное сообщение для Lefseq Посмотреть профиль Найти все сообщения от Lefseq
 
Регистрация: 19.04.2019
Сообщений: 124

рони,
https://prnt.sc/tjlix5
Ответить с цитированием
  #6 (permalink)  
Старый 17.07.2020, 16:34
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,134

Lefseq,
<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
.box-container {
  width: 232px;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
}

.box-container div {
  height: 50px;
  width: 50px;
  text-align: center;
  background-color: hsla(0, 0%, 75%, 1);
  line-height: 50px;
  position: relative;
}
.box-container div:after{
 position: absolute;
 content: attr(data-letter);
 left: 0;
 top: 0;
 width: 100%;
 background-color: hsla(167, 100%, 30%, 1);
 display: block;
 opacity: 0;
 transition-duration: 1s;
 transition-delay: var(--delay);
}
.box-container.show div:after{
 opacity: 1;
}
    </style>

</head>
<body>
<div class="box-container"></div>
<script>
document.addEventListener( "DOMContentLoaded" , function() {
class RandomFadeIn {
   constructor(str, cls, delay=1350, pause=300){
   this.parent = document.querySelector(cls);
   this.items = this.createElems(str.length, "div");
   delay = Array.from({length : str.length}, (v,k) => delay * k);
   this.items.forEach((el,i) => {
             el.textContent = i;
             el.dataset.letter = str[i];
             i = delay.length * Math.random()|0;
             i = delay.splice(i, 1)[0];
             el.style.setProperty("--delay", `${i}ms`)
          });
   this.parent.append(...this.items);
   window.setTimeout(()=> this.parent.classList.add("show"), pause);

   }
   createElems(length, tagName) {
        let elems = Array.from({length}, (v,k) => document.createElement(tagName));
        return elems
   }
}
new RandomFadeIn("FadeinImg", ".box-container")
  });
</script>


</body>
</html>
Ответить с цитированием
  #7 (permalink)  
Старый 17.07.2020, 17:16
Кандидат Javascript-наук
Отправить личное сообщение для Lefseq Посмотреть профиль Найти все сообщения от Lefseq
 
Регистрация: 19.04.2019
Сообщений: 124

рони,
Не совсем то. Текст FadeinImg это лишь пример. Мне нужно чтобы в каждой ячейке появлялась не буква из слова FadeinImg, а отдельный див с содержимым, которое я туда впишу.
Ответить с цитированием
  #8 (permalink)  
Старый 17.07.2020, 17:19
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,134

Lefseq,
будет тоже самое, только короче на 5 строк.
Ответить с цитированием
  #9 (permalink)  
Старый 17.07.2020, 17:28
Кандидат Javascript-наук
Отправить личное сообщение для Lefseq Посмотреть профиль Найти все сообщения от Lefseq
 
Регистрация: 19.04.2019
Сообщений: 124

рони,
на какие 5 строк?
Ответить с цитированием
  #10 (permalink)  
Старый 17.07.2020, 17:32
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,134

Lefseq,
<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
.box-container {
  width: 232px;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: repeat(auto-fit, minmax(50px, 1fr));
}

.box-container div {
  height: 50px;
  width: 50px;
  text-align: center;
  background-color: hsla(0, 0%, 75%, 1);
  line-height: 50px;
  position: relative;
}
.box-container div p{
 margin: 0;
 position: absolute;
 content: attr(data-letter);
 left: 0;
 top: 0;
 width: 100%;
 background-color: hsla(167, 100%, 30%, 1);
 display: block;
 opacity: 0;
 transition-duration: 1s;
 transition-delay: var(--delay);
}
.box-container.show div p{
 opacity: 1;
}
    </style>

</head>
<body>
<div class="box-container">
  <div><p>F</p></div>
  <div><p>a</p></div>
  <div><p>d</p></div>
  <div><p>e</p></div>
  <div><p>i</p></div>
  <div><p>n</p></div>
  <div><p>I</p></div>
  <div><p>m</p></div>
  <div><p>g</p></div>
</div>
<script>
document.addEventListener( "DOMContentLoaded" , function() {
class RandomFadeIn {
   constructor(cls, delay=1350, pause=300){
   this.parent = document.querySelector(cls);
   this.items = this.parent.querySelectorAll("p");
   delay = Array.from({length : this.items.length}, (v,k) => delay * k);
   this.items.forEach((el,i) => {
             el.parentNode.prepend(document.createTextNode(++i));
             i = delay.length * Math.random()|0;
             i = delay.splice(i, 1)[0];
             el.style.setProperty("--delay", `${i}ms`)
          });
   window.setTimeout(()=> this.parent.classList.add("show"), pause);
   }
}
new RandomFadeIn(".box-container")
  });
</script>


</body>
</html>
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как вы относитесь к наркоманам? Maxmaxmaximus7 Оффтопик 7 05.02.2014 13:29
Как сделать чтобы эта ссылка открывалась в этом же окне? wlad2 Общие вопросы Javascript 2 20.12.2013 05:09
Как сделать, чтобы при заходе на страницу открывались в 2-х окнах 2 ссылки ? autobuh Общие вопросы Javascript 1 26.08.2013 15:27
Как сделать так чтобы в место value использовать url чтобы картинка менялось через зн sarik Общие вопросы Javascript 9 22.02.2013 13:24
Как сделать так чтобы показывалось загрузка картинки sarik Общие вопросы Javascript 15 18.02.2013 11:27