Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Как сделать, чтобы блоки появлялись вместо уже существующих? (https://javascript.ru/forum/misc/80701-kak-sdelat-chtoby-bloki-poyavlyalis-vmesto-uzhe-sushhestvuyushhikh.html)

Lefseq 17.07.2020 13:31

Как сделать, чтобы блоки появлялись вместо уже существующих?
 
Здравствуйте. Помогите немного доработать код. Есть код, который рандомно выдает 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;
}

рони 17.07.2020 14:06

Lefseq,
:-?

Lefseq 17.07.2020 14:38

рони,
?

рони 17.07.2020 15:05

Lefseq,
попробуйте максимально просто описать, то что вы хотите сделать.

Lefseq 17.07.2020 15:35

рони,
https://prnt.sc/tjlix5

рони 17.07.2020 16:34

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>

Lefseq 17.07.2020 17:16

рони,
Не совсем то. Текст FadeinImg это лишь пример. Мне нужно чтобы в каждой ячейке появлялась не буква из слова FadeinImg, а отдельный див с содержимым, которое я туда впишу.

рони 17.07.2020 17:19

Lefseq,
будет тоже самое, только короче на 5 строк.

Lefseq 17.07.2020 17:28

рони,
на какие 5 строк?

рони 17.07.2020 17:32

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>


Часовой пояс GMT +3, время: 13:39.