Что делать, чтобы нажав за пределы всплывающего окна оно не закрывалось?

Malinka25
На сайте с 13.08.2020
Offline
2
123

Здравствуйте, нужна помощь. На сайте есть всплывающее окно, мне нужно, чтобы человек не смог закрыть его нажав за пределы этого окна.

;(function() {
    var overlay     = document.getElementById('overlay'),
        mOpen       = document.querySelectorAll('[data-modal]'),
        mClose      = document.querySelectorAll('[data-close]'),
        outer       = document.querySelector('.modal-outer'),
        modals      = document.querySelectorAll('.modal-outer > div'),
        duration    = 400,
        mStatus     = false,
        h           = null;
 
    if (mOpen.length == 0) return;
 
    setTopOuter();
 
    function setTopOuter() {
        outer.style.top = -outer.offsetHeight + 'px';
    }
 
    [].forEach.call(mOpen, function(el) {
        el.addEventListener('click', function(e) {
            var modalId = el.getAttribute('data-modal'),
                modal   = document.getElementById(modalId);
            modalShow(modal);
        });
    });
 
    [].forEach.call(mClose, function(el) {
        el.addEventListener('click', modalClose);
    });
 
    document.addEventListener('keydown', modalClose);
 
    function modalShow(modal) {
        mStatus = true;
        overlay.classList.remove('fadeOut');
        overlay.classList.add('fadeIn');
        modal.style.display = 'block';
 
        var start       = new Date().getTime(),
            startTop    = outer.getBoundingClientRect().top,
            finalTop    = (window.innerHeight - outer.offsetHeight) / 2,
            offset      = outer.offsetHeight + finalTop;
 
        var fn = function() {
            var now     = new Date().getTime() - start,
                currTop = Math.round(startTop + offset * now / duration);
 
            currTop = (currTop > finalTop) ? finalTop : currTop;
            outer.style.top = currTop + 'px';
 
            if (currTop < finalTop) {
                requestAnimationFrame(fn);
            }
        }
        requestAnimationFrame(fn);
        window.addEventListener('resize', setTopOpenOuter);
    }
 
    function modalClose(event) {
        if (mStatus && ( !event.keyCode || event.keyCode === 27 ) ) {
            mStatus = false;
 
            var start       = new Date().getTime(),
                startTop    = outer.getBoundingClientRect().top,
                finalTop    = -outer.offsetHeight,
                offset      = outer.offsetHeight + (window.innerHeight - outer.offsetHeight) / 2;
 
            var fn = function() {
                var now     = new Date().getTime() - start,
                    currTop = Math.round(startTop - offset * now / duration);
 
                currTop = (currTop < finalTop) ? finalTop : currTop;
                outer.style.top = currTop + 'px';
 
                if (currTop > finalTop) {
                    requestAnimationFrame(fn);
                } else {
                    overlay.classList.remove('fadeIn');
                    overlay.classList.add('fadeOut');
                    [].forEach.call(modals, function(modal){
                        modal.removeAttribute('style');
                    });
                }
            }
            requestAnimationFrame(fn);
            window.removeEventListener('resize', setTopOpenOuter);
        }
    }
 
    function setTopOpenOuter() {
        outer.style.top = (window.innerHeight - outer.offsetHeight) / 2 + 'px';
    }
})();
 
 
var win_top = 0;
$(document).ready(function(){
    
    // открываем модальное окно при клике по контенту
    $('#list').click(function(){
        popup_open('#myPopup');
    })
    
// открываем модальное окно через 1,5сек после загрузки страницы
 setTimeout(function() {  
      popup_open('#myPopup');  
        }, 2000);
    
    // Добавляем обработчик закрытия модального окна
    $(document).on('click', '.popup .close, .overflow', function(){
        popup_close()
        return false;
    })
    
})
function popup_open(selector){
    if (selector.length){
        win_top = $(window).scrollTop();
        $('#list').css({
            'position'  : 'fixed',
            'left'      : '0',
            'right'     : '0',
            'top'       : '0',
            // Добавляем смещение, чтобы на фоне была именно та часть, что просмаривал пользователь
            'margin-top': '-'+win_top+'px' 
        })
        $('.overflow,'+selector).fadeIn();
    }
}
function popup_close(){
    $('.overflow, .popup').hide();
    $('#list').css({
        'position'  : 'static',
        'margin-top': '0px'
    })
    // Возвращаем скролл на место
    $(window).scrollTop(win_top);
}
        <div class="overflow">
            <!-- Затемнение -->
        </div>
        <div class="popup" id="myPopup">
            <a href="#" class="close"></a>
            <div class="popup_title">Модальное окно</div>
</div>
/*Затемнение */
.overflow{
    background: rgba(0, 0, 0, 0.7);
    position:fixed;
    top: 0px;bottom: 0px;
    left: 0px;right: 0px;
    z-index:100;
    display:none;
}
/* модальное окно */
.popup{
    position:absolute;
    z-index:101;
    background: #ffffff;
    width: 435px;
    min-height: 226px;
    margin-left: -218px;
    padding: 20px;
    top: 10%;
    left: 50%;
    display:none;
    border: 0;
 -webkit-border-radius: 5px;
 -moz-border-radius: 5px; 
 border-radius: 5px;
}
 
.popup .close{
    position:absolute;
    top: 10px;
    right: 10px;
    display:block;
    width: 17px;
    height: 17px;
    opacity: 0.5;
    background: url(../img/close.png) no-repeat center;
    -webkit-transition:opacity 0.5s;
    -moz-transition:opacity 0.5s;
    transition:opacity 0.5s;
}
.popup .close:hover{
    opacity: 0.8;
}

Ghost_Dog
На сайте с 22.02.2008
Offline
99
#1

если по колхозному, то в функции modalClose

if (mStatus && ( !event.keyCode || event.keyCode === 27 ) ) {

заменяем на

if (mStatus && !event.target.classList.contains('overflow') && ( !event.keyCode || event.keyCode === 27 ) ) {
Алеандр
На сайте с 08.12.2010
Offline
189
#2
Ghost_Dog #:

если по колхозному, то в функции modalClose

заменяем на

Не проще в

$(document).on('click', '.popup .close, .overflow', function(){

убрать просто

, .overflow

?

Если верно понимаю - это исключит из обработчика клик по контейнеру, чтобы он по нему не закрывал. Глубже не вчитывался в код, но если там других обработок нет - должно помочь.

Ghost_Dog
На сайте с 22.02.2008
Offline
99
#3
Алеандр #:

Не проще в

однозначно проще 👍
я туда не дошел 😆

Авторизуйтесь или зарегистрируйтесь, чтобы оставить комментарий