1

Для практики решил написать свой JavaSript плагин для модальных окон. Решил добавить возможность анимации background'a, по идее, если функция анимации фона включена, то, фону перед его добавлением в DOM добавляется opacity: 0;, а уже после того, как фон появился в DOM-дереве, ему задается CSS класс в котором имеется свойство opacity: 1;, но по какой-то причине фон появляется резко, без анимации.

if (this.options.overlayAnimation === true) {
        this.overlay.style.opacity = '0';
        this.popUp.parentNode.insertBefore(this.overlay, this.popUp);
        this.overlay.classList.add('uzi-popup-bganimate-on');
      } else {
        this.popUp.parentNode.insertBefore(this.overlay, this.popUp);
      } 

Кусок кода, где происходит то, о чем я писал выше.

P.S. Если укажите на какие-либо ошибки или посоветуете лучший вариант реализации, буду очень благодарен.

;
(function() {

  //Create instance
  this.Modal = function() {

    //Default options
    var defaults = {
      popupSelector: null,
      openButtonSelector: null,
      animate: false,
      castumazePopup: false,
      overlayClass: false,
      popupClass: false,
    };

    //Extend default properties
    if (arguments[0] && typeof arguments[0] === 'object') {
      this.options = extendDefaults(defaults, arguments[0])
    };

    //Default UI elements
    this.openButton = document.querySelector(this.options.openButtonSelector);
    this.popUp = document.querySelector(this.options.popupSelector);
    if (this.options.closeButton) {
      this.closeButton = document.querySelector(this.options.closeButton);
    }

    //Initialize popup
    this.init();



  };



  //------------Publick methods----------------//

  Modal.prototype.init = function() {
    this.popUp.style.display = 'none';
    this.openButton.addEventListener('click', this.open.bind(this));

    if (typeof this.popupClass === 'string') {
      this.popUp.classList.add(this.popupClass);
    } else {
      var defaultStyles = {
        padding: '10px',
        position: 'absolute',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: 'white',
        zIndex: '999',
      }

      for (property in defaultStyles) {
        this.popUp.style[property] = defaultStyles[property];
      }
    }
  }

  Modal.prototype.open = function() {

    initializeEvents.call(this);

    this.addOverlay();

    computedStyles = getComputedStyle(this.popUp);
    if (computedStyles.display == 'none') {
      this.popUp.style.display = 'block'
    }
  };

  Modal.prototype.close = function() {

    this.deleteOverlay();

    computedStyles = getComputedStyle(this.popUp);
    if (computedStyles.display == 'block') {
      this.popUp.style.display = 'none'
    }
  }

  Modal.prototype.addOverlay = function() {
    if (this.options.overlay === true) {
      this.overlay = document.createElement('div');
      this.overlay.classList.add('uzi-popup-overlay');
      //Style options
      if (typeof this.options.overlayClass === 'string') {
        this.overlay.classList.add(this.options.overlayClass);
      } else {
        var defaultStyles = {
          width: '100%',
          height: '100%',
          position: 'fixed',
          top: '0',
          left: '0',
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          zIndex: '998',
          transition: '5s',
        }

        for (property in defaultStyles) {
          this.overlay.style[property] = defaultStyles[property];
        }
      }
      //Animation
      if (this.options.overlayAnimation === true) {
        this.overlay.style.opacity = '0';
        this.popUp.parentNode.insertBefore(this.overlay, this.popUp);
        this.overlay.classList.add('uzi-popup-bganimate-on');
      } else {
        this.popUp.parentNode.insertBefore(this.overlay, this.popUp);
      }


    }

    if (this.overlay) {
      this.overlay.addEventListener('click', this.close.bind(this));
    }
  }

  Modal.prototype.deleteOverlay = function() {
    if (this.overlay) {
      this.overlay.parentNode.removeChild(this.overlay);
    }
  }


  //------------Private methods----------------//

  //Extend default options function
  function extendDefaults(source, optionsArr) {
    var property;
    for (property in optionsArr) {
      if (optionsArr.hasOwnProperty(property)) {
        source[property] = optionsArr[property];
      };
    };
    return source;
  };

  //AddEventListeners
  function initializeEvents() {

    if (this.closeButton) {
      this.closeButton.addEventListener('click', this.close.bind(this));
    };




  };

  function buildOut() {


  }



}());

new Modal({
  popupSelector: '.popup',
  popupClass: false,
  openButtonSelector: 'button',
  closeButton: '.close',
  overlay: true,
  overlayAnimation: true,
})
/*Background-animation*/

.uzi-popup-bganimate {
  transition: 5s;
  opacity: 0;
}

.uzi-popup-bganimate-on {
  opacity: 1 !important;
}

body {
  background-color: red;
}
<div class="popup">
  asdasd asd

  <div class="close">close</div>
</div>
<button>button</button>

1
  • Ваш пример слишком большой, почти весь код не относится к анимации. Составьте минимальный воспроизводимый пример, выкинув всё, что не относится непосредственно к проблеме с анимацией
    – andreymal
    23 сен 2018 в 16:55

1 ответ 1

0

Реализовал на js анимацию

animateBackground = setInterval(backgroundFade, 10, this.overlay, 'show');

так и не понял где код затухания бэкграунда, как я понял он просто удаляется)

поэтому чтобы плавно спрятать бэкграунд нужно show изменить на hide

let animateBackground = null;
let speed = 0.05;
(function() {

  //Create instance
  this.Modal = function() {

    //Default options
    var defaults = {
      popupSelector: null,
      openButtonSelector: null,
      animate: false,
      castumazePopup: false,
      overlayClass: false,
      popupClass: false,
    };

    //Extend default properties
    if (arguments[0] && typeof arguments[0] === 'object') {
      this.options = extendDefaults(defaults, arguments[0])
    };

    //Default UI elements
    this.openButton = document.querySelector(this.options.openButtonSelector);
    this.popUp = document.querySelector(this.options.popupSelector);
    if (this.options.closeButton) {
      this.closeButton = document.querySelector(this.options.closeButton);
    }

    //Initialize popup
    this.init();



  };



  //------------Publick methods----------------//

  Modal.prototype.init = function() {
    this.popUp.style.display = 'none';
    this.openButton.addEventListener('click', this.open.bind(this));

    if (typeof this.popupClass === 'string') {
      this.popUp.classList.add(this.popupClass);
    } else {
      var defaultStyles = {
        padding: '10px',
        position: 'absolute',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: 'white',
        zIndex: '999',
      }

      for (property in defaultStyles) {
        this.popUp.style[property] = defaultStyles[property];
      }
    }
  }

  Modal.prototype.open = function() {

    initializeEvents.call(this);

    this.addOverlay();

    computedStyles = getComputedStyle(this.popUp);
    if (computedStyles.display == 'none') {
      this.popUp.style.display = 'block'
    }
  };

  Modal.prototype.close = function() {

    this.deleteOverlay();

    computedStyles = getComputedStyle(this.popUp);
    if (computedStyles.display == 'block') {
      this.popUp.style.display = 'none'
    }
  }

  Modal.prototype.addOverlay = function() {
    if (this.options.overlay === true) {
      this.overlay = document.createElement('div');
      this.overlay.classList.add('uzi-popup-overlay');
      //Style options
      if (typeof this.options.overlayClass === 'string') {
        this.overlay.classList.add(this.options.overlayClass);
      } else {
        var defaultStyles = {
          width: '100%',
          height: '100%',
          position: 'fixed',
          top: '0',
          left: '0',
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          zIndex: '998',
        }

        for (property in defaultStyles) {
          this.overlay.style[property] = defaultStyles[property];
        }
      }
      //Animation
      if (this.options.overlayAnimation === true) {
        this.overlay.style.opacity = '0';
        this.popUp.parentNode.insertBefore(this.overlay, this.popUp);
        animateBackground = setInterval(backgroundFade, 10, this.overlay, 'show');
      } else {
        this.popUp.parentNode.insertBefore(this.overlay, this.popUp);
      }


    }

    if (this.overlay) {
      this.overlay.addEventListener('click', this.close.bind(this));
    }
  }

  Modal.prototype.deleteOverlay = function() {
    if (this.overlay) {
      this.overlay.parentNode.removeChild(this.overlay);
    }
  }


  //------------Private methods----------------//

  //Extend default options function
  function extendDefaults(source, optionsArr) {
    var property;
    for (property in optionsArr) {
      if (optionsArr.hasOwnProperty(property)) {
        source[property] = optionsArr[property];
      };
    };
    return source;
  };

  //AddEventListeners
  function initializeEvents() {

    if (this.closeButton) {
      this.closeButton.addEventListener('click', this.close.bind(this));
    };




  };

  function buildOut() {


  }



}());

function backgroundFade(target, type) {
  let op = Number(target.style.opacity);
  if (op < 0 || op > 1) {
    clearInterval(animateBackground);
  }
  if (type == 'show') {
    op += speed;
  } else if (type == 'hide') {
    op -= speed;
  }
  target.style.opacity = String(op);
}


new Modal({
  popupSelector: '.popup',
  popupClass: false,
  openButtonSelector: 'button',
  closeButton: '.close',
  overlay: true,
  overlayAnimation: true,
})
/*Background-animation*/

.uzi-popup-bganimate {
  opacity: 0;
}

body {
  background-color: red;
}
<div class="popup">
  asdasd asd

  <div class="close">close</div>
</div>
<button>button</button>

3
  • «так и не понял где код затухания бэкграунда» — ну то есть на вопрос так и не ответили
    – andreymal
    23 сен 2018 в 16:56
  • Он не мой . . .
    – andreymal
    23 сен 2018 в 17:12
  • Но это не объяняет, почему вы путаете меня с автором вопроса
    – andreymal
    23 сен 2018 в 17:14

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.