JQuery Видеть сквозное диалоговое наложение - PullRequest
3 голосов
/ 31 августа 2011

Есть несколько плагинов JQuery, чтобы разместить модальное диалоговое окно и показать в нем элемент dom. Но я ищу диалоговое наложение, которое может показать некоторую часть экрана, и эти области должны быть доступны, в то время как другие элементы должны быть заблокированы.

Ответы [ 5 ]

5 голосов
/ 31 августа 2011

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

Основное использование выглядит следующим образом (обратите внимание, что если ваш селектор соответствует нескольким элементам, он просто замаскирует первый):

$("#yourDiv").mask();

Маскировка другого элемента снимает маскировку с других маскируемых элементов, или вы можете явно снять маскировку с помощью:

$("#yourDiv").unmask();

Плагин-код:

(function( $ ){
    $.fn.mask = function() {
        this.unmask();

        var totalWidth = $(document).width();
        var totalHeight = $(document).height();

        var target = this.first();
        var maskWidth = target.outerWidth();
        var maskHeight = target.outerHeight();
        var maskOffset = target.offset();

        addMask(0, 0, maskOffset.left, totalHeight);                                                                    //left
        addMask(maskOffset.left + maskWidth, 0, totalWidth - (maskOffset.left + maskWidth), totalHeight);                 //right
        addMask(maskOffset.left, 0, maskWidth, maskOffset.top);                                                         //top
        addMask(maskOffset.left, maskOffset.top + maskHeight, maskWidth, totalHeight - (maskOffset.top + maskHeight));    //bottom

        var btn = $("<input type='button' value='Cancel' class='mask' />");
        $("body").append(btn);
        btn.css({ position: "absolute", zIndex: 9999, top: (maskOffset.top + maskHeight + 5), left: (maskOffset.left + maskWidth - btn.outerWidth(true)) });
        btn.click(function() { $(this).unmask(); });

        return this;
    };
    $.fn.unmask = function() {
        $(".mask").fadeOut(function() { $(this).remove(); });
    };

    function addMask(x, y, w, h) {
        var mask = $("<div class='mask'></div>");
        mask.css({ position: "absolute", zIndex: 9999, width: w, height: h, top: y, left: x, display: "none" });
        //comment out this line & replace with css styles on 'div.mask' if you want to customise
        mask.css({ backgroundColor: "#000", opacity: 0.3, filter: "alpha(opacity=30)" });
        $("body").append(mask);
        mask.fadeIn();
        // mask.click(function() { $(this).unmask(); });
    }
})( jQuery );

Редактировать : исправлена ​​ошибка с размерами панели, добавлен эффект исчезновения и теперь удаляет маску, если вы щелкаете за пределами маскирегион имеет кнопку отмены для удаления маски.

Изменить 2 : JsFiddle demo

0 голосов
/ 31 августа 2011

Ответ Алконьи более изящен, чем этот, и это действительно означает скорее демонстрацию, но вы можете увидеть здесь, что происходит.Наложение - это сетка с восемью блоками, а средний блок является областью формы, которая является открытой.

Убедитесь, что проверьте элементы с помощью консоли Firebug или Chrome, чтобы увидеть, как отображаются элементы, и стили CSSприменяется.

<div id="wrapper">
    <div id="test">
        <div>
            Text: <input type="text"/> <input type="button" value="Undo"/>
        </div>
        <div>
            Text: <input type="text"/> <input type="button"value="Undo"/>
        </div>
        <div>
            Text: <input type="text"/> <input type="button"value="Undo"/>
        </div>
    </div>
</div>

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#wrapper {
  min-height: 100%;
  padding: 0;
  margin: 0;
  overflow: auto;
}
#test {
  background: #ddd;
  margin: 0 auto;
  padding: 0;
  width: 330px;
}
#test div {
  background: #ffa;
  margin: 20px;
  padding: 20px;
}
.overlay {
  background: #dda;
  opacity: .6;
  position: absolute;
  z-index: 1000;
}

function setOverlay(top, left, width, height) {
    var screenwidth = parseInt($('body').width());
    var screenheight = parseInt($('body').height());
    var topleft = [0, 0, left, top];
    $('<div class="overlay" style="top: '+topleft[0]+'px; '+
                  'left: '+topleft[1]+'px; '+
                  'width: '+topleft[2]+'px; '+
                  'height: '+topleft[3]+'px;"></div>').appendTo('body');
    var topmiddle = [0, left, width, top];
    $('<div class="overlay" style="top: '+topmiddle[0]+'px; '+
                  'left: '+topmiddle[1]+'px; '+
                  'width: '+topmiddle[2]+'px; '+
                  'height: '+topmiddle[3]+'px;"></div>').appendTo('body');
    var topright = [0, left+width, screenwidth-left-width, top];
    $('<div class="overlay" style="top: '+topright[0]+'px; '+
                  'left: '+topright[1]+'px; '+
                  'width: '+topright[2]+'px; '+
                  'height: '+topright[3]+'px;"></div>').appendTo('body');
    var centerleft = [top, 0, left, height];
    $('<div class="overlay" style="top: '+centerleft[0]+'px; '+
                  'left: '+centerleft[1]+'px; '+
                  'width: '+centerleft[2]+'px; '+
                  'height: '+centerleft[3]+'px;"></div>').appendTo('body');
    var centerright = [top, left+width, screenwidth-left-width, height];
    $('<div class="overlay" style="top: '+centerright[0]+'px; '+
                  'left: '+centerright[1]+'px; '+
                  'width: '+centerright[2]+'px; '+
                  'height: '+centerright[3]+'px;"></div>').appendTo('body');
    var bottomleft = [top+height, 0, left, screenheight-top-height];
    $('<div class="overlay" style="top: '+bottomleft[0]+'px; '+
                  'left: '+bottomleft[1]+'px; '+
                  'width: '+bottomleft[2]+'px; '+
                  'height: '+bottomleft[3]+'px;"></div>').appendTo('body');
    var bottommiddle = [top+height, left, width, screenheight-top-height];
    $('<div class="overlay" style="top: '+bottommiddle[0]+'px; '+
                  'left: '+bottommiddle[1]+'px; '+
                  'width: '+bottommiddle[2]+'px; '+
                  'height: '+bottommiddle[3]+'px;"></div>').appendTo('body');
    var bottomright = [top+height, left+width, screenwidth-left-width, screenheight-top-height];
    $('<div class="overlay" style="top: '+bottomright[0]+'px; '+
                  'left: '+bottomright[1]+'px; '+
                  'width: '+bottomright[2]+'px; '+
                  'height: '+bottomright[3]+'px;"></div>').appendTo('body');
}
$(document).ready(function(){
    $('input[type="text"]').focus(function(){
        $this = $(this).parent();
        $('input[value="Undo"]').click();
        setOverlay(
            parseInt($this.offset().top),
            parseInt($this.offset().left),
            parseInt($this.outerWidth()),
            parseInt($this.outerHeight())
        );
    });
    $('input[value="Undo"]').click(function(){
        $('.overlay').remove();        
    });
});

http://jsfiddle.net/userdude/3nRLJ/

0 голосов
/ 31 августа 2011

Я использую плагин BlockUI . Позволяет блокировать всю страницу или отдельные элементы.

0 голосов
/ 31 августа 2011

Хотя мне неприятно предлагать библиотеку jQuery Tools, то, что вы ищете, называется «expose» http://flowplayer.org/tools/demos/toolbox/expose/index.html

0 голосов
/ 31 августа 2011

Создайте z-index для элементов, которые вы хотите показать больше, чем тот, который имеет наложение ПРИМЕЧАНИЕ. Помните, что z-index является относительным, и будьте осторожны с ним.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...