Jump to content
  • Sign Up
  • 0

Интересная JQuery задачка


Alarr
 Share

Question

Есть два контейнера, в каждом по 4 дива.

https://jsfiddle.net/y3L89Ldf/

 

Как можно сделать так, что бы каждые две секунды, рандомный блок из верхнего контейнера менялся на рандомный блок из нижнего?

И так, что бы в верхнем контейнере не было одинаковых блоков, и что бы верхний блок, не менялся два раза подряд на один из нижних.

 

Походу надо сделать что бы при смене верхнего блока, он менялся местами с нижним, что бы нижний потом тоже мог рандомно стать обратно в верхний контейнер?

 

Спасибо тем, кому будет интересно одолеть задачу:)

Link to comment
Share on other sites

4 answers to this question

Recommended Posts

  • 0

https://jsfiddle.net/Andrey7287/y3L89Ldf/6/

Крутизна!:) А как можно сделать так, что бы оно фейдом изменялось? Заюзать анимэйт?

А можно ли сделать так, что бы определённые блоки не менялись? Это надо юзать not ?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Similar Content

    • Kaido
      By Kaido
      Использую готовый плагин для модальных окон(от MaxGraph). Проблема в том, что когда у меня открыто два модальных окна, для примера Форма + Политика конфендициальности, и мне нужно закрыть политику вместе с ней закрывается и другое модальное окно. В JS я не сильно разбираюсь(собственно из за этого и использую готовый плагин), можете помочь кто работал с этим плагином? Я примерно понимаю как он работает, но реализовать чтобы закрывалось только одно не получается.
       
        <div class="content"> <button class="modal-btn" data-path="first" data-animation="fadeInUp" data-speed="1500">Открыть окно 1</button> </div> <div class="modal"> <div class="modal__wrapp" data-target="first"> <div class="modal__content"> <button class="modal__close">Закрыть</button> модальное окно <button data-path="policy">Политика</button> </div> </div> <div class="modal__wrapp" data-target="policy"> <div class="modal__content"> <button class="modal__close">Закрыть</button> политика </div> </div> </div> .modal { --transition-time: 0.3s; position: fixed; left: 0; top: 0; right: 0; bottom: 0; z-index: 1000; cursor: pointer; overflow-y: auto; overflow-x: hidden; text-align: center; opacity: 0; visibility: hidden; transition: opacity var(--transition-time), visibility var(--transition-time); } .modal__wrapp { display: none; cursor: default; width: fit-content; height: fit-content; } .modal__content{ position: absolute; left: 500px; width: 500px; height: 500px; display: flex; color: white; flex-direction: column; text-align: left; background-color: #000; } .modal__content button{ width: 200px; height: 50px; margin: 50px 0; } .modal.is-open { opacity: 1; visibility: visible; transition: opacity var(--transition-time), visibility var(--transition-time); } .modal__wrapp.modal-open { display: flex; } .disable-scroll { position: relative; overflow: hidden; height: 100vh; position: fixed; left: 0; top: 0; width: 100%; } .fade { opacity: 0; transition: opacity var(--transition-time); } .fade.animate-open { opacity: 1; transition: opacity var(--transition-time); } .fadeInUp { opacity: 0; transform: translateY(vw(-100)); transition: opacity var(--transition-time), transform var(--transition-time); } .fadeInUp.animate-open { opacity: 1; transform: translateY(0); transition: opacity var(--transition-time), transform var(--transition-time); } .modal__wrapp[data-target="policy"] .modal__content{ left: 1050px; background-color: #000; opacity: .5; } class Modal { constructor(options) { let defaultOptions = { isOpen: () => {}, isClose: () => {}, } this.options = Object.assign(defaultOptions, options); this.modal = document.querySelector('.modal'); this.speed = false; this.animation = false; this.isOpen = false; this.modalContainer = false; this.previousActiveElement = false; this.fixBlocks = document.querySelectorAll('.fix-block'); this.focusElements = [ 'a[href]', 'input', 'button', 'select', 'textarea', '[tabindex]' ]; this.events(); } events() { if (this.modal) { document.addEventListener('click', function(e){ const clickedElement = e.target.closest('[data-path]'); if (clickedElement) { let target = clickedElement.dataset.path; let animation = clickedElement.dataset.animation; if (clickedElement.classList.contains('modal-close')) { this.close(); } let speed = clickedElement.dataset.speed; this.animation = animation ? animation : 'fade'; this.speed = speed ? parseInt(speed) : 300; this.modalContainer = document.querySelector(`[data-target="${target}"]`); this.open(); return; } if (e.target.closest('.modal__close')) { this.close(); return; } }.bind(this)); window.addEventListener('keydown', function(e) { if (e.keyCode == 27) { if (this.isOpen) { this.close(); } } if (e.keyCode == 9 && this.isOpen) { this.focusCatch(e); return; } }.bind(this)); this.modal.addEventListener('click', function(e) { if (!e.target.classList.contains('modal__wrapp') && !e.target.closest('.modal__wrapp') && this.isOpen) { this.close(); } }.bind(this)); } } open() { this.previousActiveElement = document.activeElement; this.modal.style.setProperty('--transition-time', `${this.speed / 1000}s`); this.modal.classList.add('is-open'); this.disableScroll(); this.modalContainer.classList.add('modal-open'); this.modalContainer.classList.add(this.animation); setTimeout(() => { this.options.isOpen(this); this.modalContainer.classList.add('animate-open'); this.isOpen = true; this.focusTrap(); }, this.speed); } close() { if (this.modalContainer) { this.modalContainer.classList.remove('animate-open'); this.modalContainer.classList.remove(this.animation); this.modal.classList.remove('is-open'); this.modalContainer.classList.remove('modal-open'); this.enableScroll(); this.options.isClose(this); this.isOpen = false; this.focusTrap(); } } focusCatch(e) { const focusable = this.modalContainer.querySelectorAll(this.focusElements); const focusArray = Array.prototype.slice.call(focusable); const focusedIndex = focusArray.indexOf(document.activeElement); if (e.shiftKey && focusedIndex === 0) { focusArray[focusArray.length - 1].focus(); e.preventDefault(); } if (!e.shiftKey && focusedIndex === focusArray.length - 1) { focusArray[0].focus(); e.preventDefault(); } } focusTrap() { const focusable = this.modalContainer.querySelectorAll(this.focusElements); if (this.isOpen) { focusable[0].focus(); } else { this.previousActiveElement.focus(); } } disableScroll() { let pagePosition = window.scrollY; this.lockPadding(); document.body.classList.add('disable-scroll'); document.body.dataset.position = pagePosition; document.body.style.top = -pagePosition + 'px'; } enableScroll() { let pagePosition = parseInt(document.body.dataset.position, 10); this.unlockPadding(); document.body.style.top = 'auto'; document.body.classList.remove('disable-scroll'); window.scroll({ top: pagePosition, left: 0 }); document.body.removeAttribute('data-position'); } lockPadding() { let paddingOffset = window.innerWidth - document.body.offsetWidth + 'px'; this.fixBlocks.forEach((el) => { el.style.paddingRight = paddingOffset; }); document.body.style.paddingRight = paddingOffset; } unlockPadding() { this.fixBlocks.forEach((el) => { el.style.paddingRight = '0px'; }); document.body.style.paddingRight = '0px'; } } const modal = new Modal({ isOpen: (modal) => { console.log(modal); console.log('opened'); }, isClose: () => { console.log('closed'); }, });  
    • ilyamio
      By ilyamio
      Здравствуйте. Имеется рабочий скрипт конвертера валют. https://ilyamio.github.io/currencyconverter/
      Мне необходимо изменить источник загрузки курсов на ЦБ РФ вот по этой ссылке: https://www.cbr.ru/scripts/XML_daily.asp
      А также мне необходимо установить ограничение на количество обращений к сайту ЦБ РФ - 1 раз в сутки. При частом обращении, могут заблокировать.
      Вот в этом js файле находятся настройки конвертера:
      const from_currencyEl = document.getElementById('from_currency'); const from_ammountEl = document.getElementById('from_ammount'); const to_currencyEl = document.getElementById('to_currency'); const to_ammountEl = document.getElementById('to_ammount'); const rateEl = document.getElementById('rate'); const exchange = document.getElementById('exchange'); from_currencyEl.addEventListener('change', calculate); from_ammountEl.addEventListener('input', calculate); to_currencyEl.addEventListener('change', calculate); to_ammountEl.addEventListener('input', calculate); exchange.addEventListener('click', () => { const temp = from_currencyEl.value; from_currencyEl.value = to_currencyEl.value; to_currencyEl.value = temp; calculate(); }); function calculate() { const from_currency = from_currencyEl.value; const to_currency = to_currencyEl.value; fetch(`https://api.exchangerate-api.com/v4/latest/${from_currency}`) .then(res => res.json()) .then(res => { const rate = res.rates[to_currency]; rateEl.innerText = `1 ${from_currency} = ${rate} ${to_currency}` to_ammountEl.value = (from_ammountEl.value * rate).toFixed(2); }) } calculate(); Как мне изменить настройки в этом файле чтобы курсы брались с https://www.cbr.ru/scripts/XML_daily.asp и включить ограничение на количество обращений по ссылке cbr.ru - 1 раз в сутки?
      Заранее спасибо всем, кто хотел помочь с решением этой задачи.
    • vasyl_runner
      By vasyl_runner
      $(function () { var mixer = mixitup('.directions__list'); $('.directions__filter-btn').on('click', function () { $('.directions__filter-btn').removeClass('directions__filter-btn--active') $(this).addClass('directions__filter-btn--active') }) })
    • Yurich
      By Yurich
      Всем привет, у меня такой вот вопрос, делаю сайт через react и при изменении расширения что-то идёт не так и какой-то бред получается, подскажите как решить данную проблему. Я вообще не понимаю из-за чего это происходит, по этому не могу нормально объяснить 😅.

    • jksnf
      By jksnf
      Не работает transition при появлений модального окна:
      <a class="btn">Modal</a> <div class="modal"> <div class="overlay"> <div class="content"> <a class="close">X</a> <h1>Title</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sunt repellat asperiores rerum animi officiis minus corporis iure voluptate accusantium, ut optio ratione iusto nemo delectus. Quasi illum libero dolorum neque?</p> </div> </div> </div> //scss .modal .overlay{ position: fixed; top: 0;left: 0; width: 100%;height: 100%; background: rgba($color: #000000, $alpha: .8); z-index: 1; display: none; } .modal .content{ width: 500px;height: 200px; position: absolute; top: 50%;left: 50%; transform: translate(-50%, -50%); background-color: #fff; z-index: 2; text-align: center; display: none; a{ line-height: 30px; font-weight: bold; color: #fff; top: -50px;; position: absolute; right: -50px; font-size: 40px; padding: 10px; } h1{ margin-bottom: 20px; } } .modal.active .overlay{ display: block; } .modal.active .content{ display: block; } //Jquery $(document).ready(function(){ $(".btn, .close").click(function() { $(".modal").toggleClass("active") }) }) Я понимаю что на display не работает transition. но и нельзя ставить opacity т.к перекрывает контент сзади него изначально.

      Что делать?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy