Модальный диалог без jQuery - программирование
Подтвердить что ты не робот

Модальный диалог без jQuery

Мне нужно создать модальный диалог на веб-странице с помощью javascript. Обычно это было бы легко, поскольку я мог бы использовать что-то вроде jQueryUI или BlockUI, но здесь предостережение заключается в том, что мне не разрешено использовать jQuery, и мне нужно поддерживать режим quirks IE9 (то есть без html5 doctype). Я не могу найти что-либо в Интернете относительно того, что мне нужно. У кого-нибудь есть предложения? Спасибо.

4b9b3361

Ответ 1

Как насчет наложения с центром в центре?

У вас может быть div, который вы можете скрыть (используя javascript):

 <div id="overlay">
  <div>
      <p>Content you want the user to see goes here.</p>
  </div>
 </div>

Стиль CSS для наложения может выглядеть следующим образом:

 #overlay {
    visibility: hidden;
    position: absolute;
    left: 0px;
    top: 0px;
    width:100%;
    height:100%;
    text-align:center;
    z-index: 1000;
 }

Чем вы можете использовать javascript для переключения видимости содержимого в divaly div:

 function overlay() {
    el = document.getElementById("overlay");
   el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
 }

Подробнее здесь: http://raventools.com/blog/create-a-modal-dialog-using-css-and-javascript/

Ответ 2


Я создал библиотеку под названием tomloprodModal, которая делает то, что вам нужно. Это простая и настраиваемая библиотека javascript для создания гибких и минималистических модальных окон без зависимостей.

Надеюсь, это поможет вам.


Установка:

Просто скачайте и добавьте tomloprodModel.css и tomloprodModel. js на ваш сайт.

Вы также можете использовать беседу: bower install tomloprodModal или используя npm: npm install tomloprodModal


Инициализация:

JavaScript:

TomloprodModal.start({
    closeOut: true,
    bgColor: "#FFFFFF",
    textColor: "#333333"
});

Пример модального окна:

<div class="tm-modal tm-effect tm-draggable" id="logInPopUp">
    <div class="tm-wrapper">
        <div class="tm-title">
            <span class="tm-XButton tm-closeButton"></span>  
            <h3 class="tm-title-text">Lorem Ipsum...</h3> 
        </div>
        <div class="tm-content" >
            <div style="text-align:center">
                <img width="250" src="http://s3.favim.com/orig/47/animal-cat-cute-kitty-surprise-Favim.com-434324.jpg"/>
            </div>
            <p>
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt.
            </p>
        </div>
    </div>
</div>

Результат:

введите описание изображения здесь


Или вы можете создать модальное окно без какого-либо HTML:

TomloprodModal.create({
    bgColor: "#FFFFFF",
    textColor: "#333333",
    title: "Hi!",
    content: "Nothing to say",
    closeTimer: 1000
});

Документация:

https://github.com/tomloprod/tomloprodModal


Демо:

http://codepen.io/tomloprod/pen/kkYxWY

Ответ 3

Я написал несколько простых функций JavaScript для этой цели, а также демонстрационную страницу, чтобы показать вам, как их использовать. Вы можете просмотреть это на http://www.interbit.com/demos/modal.html.

Функции, которые я написал, называются MsgBox(), YesNo() и YesNoCancel(). Они делают то, что подразумевают их имена.

Чтобы использовать их, просто создайте копию файла JavaScript по указанной выше ссылке и включите ее в свой HTML. Пожалуйста, не просто ссылку на файл. Скорее сделайте копию, потому что я могу изменить его или снять его в любое время.

Примеры:

MsgBox("This is a message for the user.", "This is the title");
MsgBox("This is a message for the user.", "This is the title", "JSSnippetToCall();");
YesNo("Are you sure you want to do this?", "Please Confirm", "JSSnippetToCallOnYes();", "JSSnippetToCallOnNo();");
YesNoCancel("Are you sure you want to do this?", "Please Confirm", "JSSnippetToCallOnYes();", "JSSnippetToCallOnNo();", "JSSnippetToCallOnCancel();");

Я также включил функцию JavaScriptError(), которая принимает объект JavaScript Error и форматирует его для отображения пользователю, подходящего для использования в блоке try/catch:

try {
    <your JavaScript code here>
} catch (e) {
    JavaScriptError(e);
}

Здесь приведен полный список кода, как предложил один из комментаторов. Вы можете включить его во все ваши проекты. У меня есть некоторые забавные комментарии о том, как я хочу, чтобы вы дали мне кредит, но на самом деле все, о чем я прошу, является общепринятой вежливостью. Я действительно не собираюсь подавать в суд на кого-либо, если вы не украдете код и не заявили, что написали его.

/**************************************************************************************************/
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/**************************************************************************************************/
/* The functions below are each self-contained and can be copied into any HTML file by themselves
/* and used.  The CSS styling is accomplished by using the STYLE attribute on each HTML tag.  There
/* is no need to use external CSS.  Of course, once you copy the code you can modify it to suit
/* your needs, including changing the styling.  But be careful, especially with the msgBoxDivStyle,
/* because some of it is necessary to achieve the desired effect.
/*
/* You are free to simply copy this JavaScript code into your application, as long as you include
/* the copyright notice in each copy of the code you make.  No exceptions.  If you don't, and I
/* find out, I'll sue you for enough money to retire on.  Because that just rude and rude 
/* people need to be sued to make the world a better place.  You are also free to modify the code
/* to suit your needs.  But if you do, you still need to give me credit.
/*
/* To see how these functions can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/*
/* I recognize that this code could easily have been written more efficiently, and without some of
/* the redundancy.  I intentionally wrote it the way I did to make it more easily understandable
/* and modifiable to meet your needs.
/**************************************************************************************************/

/**************************************************************************************************/
/* Function MsgBox
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: Message, WindowTitle, onOK
/* Description: This function displays a modal message box with a single OK button.
/*              When the user clicks the OK button the box is removed and the JavaScript provided
/*              in the onOK parameter, if any, is called.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function MsgBox(msg, title, onOK) {

    try {
        var msgBoxDivStyle = "background: rgba(127, 127, 127, 0.6);height: 100%;position: absolute;width: 100%;z-index: 9999;";
        var msgBoxTitleStyle = "background-color: #00478A;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxErrorTitleStyle = "background-color: red;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxSuccessTitleStyle = "background-color: green;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxWarningTitleStyle = "background-color: orange;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxContentsStyle = "background: rgba(255, 255, 255, 1);background-color: white;border: 1px solid black;box-shadow: 6px 6px 6px #070707;";
        msgBoxContentsStyle += "left: 30%;position: absolute;resize: vertical;text-align: center;top: 15%;width: 40%;";
        var msgBoxTextStyle = "font-size: 18px;overflow: auto;padding: 20px;text-align: center;";
        var msgBoxButtonStyle = "margin: 20px;";

        var msgDiv = "";

        if (title == null) {
            title = "Information";
        }

        if (onOK == null) {
            onOK = "";
        }

        titleStyle = msgBoxTitleStyle;
        if (title == "Error" || title == "JavaScript Error" || title == "Exception") {
            titleStyle = msgBoxErrorTitleStyle;

        } else if (title == "Success") {
            titleStyle = msgBoxSuccessTitleStyle;

        } else if (title == "Warning") {
            titleStyle = msgBoxWarningTitleStyle;
        }

        msgDiv += "<div id='msgboxDiv' style='" + msgBoxDivStyle + "'>";  // Covers the entire body to prevent any interaction with controls in the body.
        msgDiv += "<div id='msgboxContents' style='" + msgBoxContentsStyle + "'>";  // Contains the messagebox itself
        msgDiv += "<div id='msgboxTitle' style='" + titleStyle + "'>" + title + "</div>";
        msgDiv += "<div id='msgboxText' style='" + msgBoxTextStyle + "'>" + msg + "</div>";  // Contains the text of the message to be displayed.
        msgDiv += "<button id='answerOK' tabindex='1' style='" + msgBoxButtonStyle + "' accesskey='K' onclick='" + onOK + "document.body.removeChild(this.parentElement.parentElement);'>O<u>K</u></button>";
        msgDiv += "</div></div>";  // Closes the modalBox and modalDiv tags

        document.body.insertAdjacentHTML("afterBegin", msgDiv);

        // This next line is necessary so that the new elements can be referred to in the following JavaScript code.
        document.body.focus();

        // Disable the tab key so that the user can't use it to get to the other controls on the page.
        document.getElementById('answerOK').onkeydown = function(e){if(e.keyCode==9){return false;}}
        document.getElementById('answerOK').focus();

    } catch (e) {
        JavaScriptError(e);
    }
}


/**************************************************************************************************/
/* Function YesNo
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: Message, WindowTitle, onYes, onNo
/* Description: This function displays a modal message box with two buttons labeled "Yes" and "No".
/*              When the user clicks either button the box is removed and the appropriate
/*              JavaScript (passed in the onYes and onNo parameters) is executed.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function YesNo(msg, title, onYes, onNo) {

    try {
        var msgBoxDivStyle = "background: rgba(127, 127, 127, 0.6);height: 100%;position: absolute;width: 100%;z-index: 9999;";
        var msgBoxTitleStyle = "background-color: #00478A;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxErrorTitleStyle = "background-color: red;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxSuccessTitleStyle = "background-color: green;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxWarningTitleStyle = "background-color: orange;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxContentsStyle = "background: rgba(255, 255, 255, 1);background-color: white;border: 1px solid black;box-shadow: 6px 6px 6px #070707;";
        msgBoxContentsStyle += "left: 30%;position: absolute;resize: vertical;text-align: center;top: 15%;width: 40%;";
        var msgBoxTextStyle = "font-size: 18px;overflow: auto;padding: 20px;text-align: center;";
        var msgBoxButtonStyle = "margin: 20px;";

        var msgDiv = "";

        if (title == null) {
            title = "Confirm";
        }

        if (onYes == null) {
            onYes = "";
        }

        if (onNo == null) {
            onNo = "";
        }

        msgDiv += "<div id='msgboxDiv' style='" + msgBoxDivStyle + "'>";  // Covers the entire body to prevent any interaction with controls in the body.
        msgDiv += "<div id='msgboxContents' style='" + msgBoxContentsStyle + "'>";  // Contains the messagebox itself
        msgDiv += "<div id='msgboxTitle' style='" + msgBoxTitleStyle + "'>" + title + "</div>";
        msgDiv += "<div id='msgboxText' style='" + msgBoxTextStyle + "'>" + msg + "</div>";  // Contains the text of the message to be displayed.
        msgDiv += "<button id='answerYes' tabindex='1' style='" + msgBoxButtonStyle + "' accesskey='Y' onclick='" + onYes + "document.body.removeChild(this.parentElement.parentElement);'><u>Y</u>es</button>";
        msgDiv += "<button id='answerNo' tabindex='2' style='" + msgBoxButtonStyle + "' accesskey='N' onclick='" + onNo + "document.body.removeChild(this.parentElement.parentElement);'><u>N</u>o</button>";
        msgDiv += "</div></div>";  // Closes the modalBox and modalDiv tags

        document.body.insertAdjacentHTML("afterbegin", msgDiv);

        // This next line is necessary so that the new elements can be referred to in the following JavaScript code.
        document.body.focus();

        // Intercept the tab key so that the user can't use it to get to the other controls on the page.
        document.getElementById('answerYes').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerNo').focus();return false;}}
        document.getElementById('answerNo').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerYes').focus();return false;}}

        // Put the user focus on the Yes button.
        document.getElementById('answerYes').focus();

    } catch (e) {
        JavaScriptError(e);
    }
}


/**************************************************************************************************/
/* Function YesNoCancel
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: Message, WindowTitle, Callback
/* Description: This function displays a modal message box with three buttons labeled "Yes", "No",
/*              and "Cancel".  When the user clicks any of the buttons the box is removed and the
/*              appropriate JavaScript (passed in the onYes, onNo, and onCancel parameters)
/*              is called, if any.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function YesNoCancel(msg, title, onYes, onNo, onCancel) {

    try {
        var msgBoxDivStyle = "background: rgba(127, 127, 127, 0.6);height: 100%;position: absolute;width: 100%;z-index: 9999;";
        var msgBoxTitleStyle = "background-color: #00478A;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxErrorTitleStyle = "background-color: red;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxSuccessTitleStyle = "background-color: green;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxWarningTitleStyle = "background-color: orange;color: white;font-size: 20px;font-weight: bold;left: 0px;padding: 4px;text-align: left;top: 0px;";
        var msgBoxContentsStyle = "background: rgba(255, 255, 255, 1);background-color: white;border: 1px solid black;box-shadow: 6px 6px 6px #070707;";
        msgBoxContentsStyle += "left: 30%;position: absolute;resize: vertical;text-align: center;top: 15%;width: 40%;";
        var msgBoxTextStyle = "font-size: 18px;overflow: auto;padding: 20px;text-align: center;";
        var msgBoxButtonStyle = "margin: 20px;";

        var msgDiv = "";

        if (title == null) {
            title = "Confirm";
        }

        if (onYes == null) {
            onYes = "";
        }

        if (onNo == null) {
            onNo = "";
        }

        if (onCancel == null) {
            onCancel = "";
        }

        msgDiv += "<div id='msgboxDiv' style='" + msgBoxDivStyle + "'>";  // Covers the entire body to prevent any interaction with controls in the body.
        msgDiv += "<div id='msgboxContents' style='" + msgBoxContentsStyle + "'>";  // Contains the messagebox itself
        msgDiv += "<div id='msgboxTitle' style='" + msgBoxTitleStyle + "'>" + title + "</div>";
        msgDiv += "<div id='msgboxText' style='" + msgBoxTextStyle + "'>" + msg + "</div>";  // Contains the text of the message to be displayed.
        msgDiv += "<button id='answerYes' tabindex='1' style='" + msgBoxButtonStyle + "' accesskey='Y' onclick='document.body.removeChild(this.parentElement.parentElement);" + onYes + "'><u>Y</u>es</button>";
        msgDiv += "<button id='answerNo' tabindex='2' style='" + msgBoxButtonStyle + "' accesskey='N' onclick='document.body.removeChild(this.parentElement.parentElement);" + onNo + "'><u>N</u>o</button>";
        msgDiv += "<button id='answerCancel' tabindex='3' style='" + msgBoxButtonStyle + "' accesskey='C' onclick='document.body.removeChild(this.parentElement.parentElement);" + onCancel + "'><u>C</u>ancel</button>";
        msgDiv += "</div></div>";  // Closes the modalBox and modalDiv tags

        document.body.insertAdjacentHTML("afterbegin", msgDiv);

        // This next line is necessary so that the new elements can be referred to in the following JavaScript code.
        document.body.focus();

        // Intercept the tab key so that the user can't use it to get to the other controls on the page.
        document.getElementById('answerYes').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerNo').focus();return false;}}
        document.getElementById('answerNo').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerCancel').focus();return false;}}
        document.getElementById('answerCancel').onkeydown = function(e){if(e.keyCode==9){document.getElementById('answerYes').focus();return false;}}

        // Put the user focus on the Yes button.
        document.getElementById('answerYes').focus();

    } catch (e) {
        JavaScriptError(e);
    }

}


/**************************************************************************************************/
/* Function JavaScriptError
/* Copyright 2016.  Matthew G. Collins.  All rights reserved.
/* Parameters: JavaScript Error Object
/* Description: This function formats and uses the MsgBox function to display a JavaScript Error.
/*
/* To see how this function can be used in practice to give the effect of a modal dialog box
/* see the demonstration page at http://www.interbit.com/demos/modal.html.
/**************************************************************************************************/
function JavaScriptError(e) {

    var msg = "";

    try {
        msg = e.name + "<br /><br />" + e.message + "<br /><br />" + e.stack;

    } catch (e) {
        msg = e.message;
    }

    try {
        MsgBox(msg, "JavaScript Error");

    } catch (e1) {
        alert(msg);
    }
}


/**************************************************************************************************/
/* Function jsonError
/* Parameters: JSON object with the following properties: errNumber, errMessage.
/*             The JSON object may have additional properties, but it will only use the errNumber
/*             and errMessage properties.
/* Description: This function formats and displays a JSON error.
/**************************************************************************************************/
function jsonError(err) {
    msg = "Error " + err.errNumber + "<br /><br />";
    msg += err.errMessage + "<br /><br />";
    MsgBox(msg, "Exception");
}

Ответ 4

ModaliseJS, легче tomloprodModal и совместим с любым CSS.

HTML: (опустите modalise.css, если у вас есть собственный дизайн или использование начальной загрузки)

<!DOCTYPE html>
<html>
<head>
    <title>Modal example</title>
    <link href="../../dist/modalise.css" rel="stylesheet">
    <script src="../../dist/modalise.js" type="text/javascript">
    </script>
    <script src="app.js" type="text/javascript">
    </script>
</head>
<body>
    <h1>Example modal 1</h1><button id="openModal">Show the modal</button>
    <div class="mdl mdl-fadein" id="exampleModal">
        <div class="mdl-content mdl-slidein">
            <center>
                <div class="mdl-header mdl-band-primary">
                    <span class="close">X</span>
                    <h2>Example modal</h2>
                </div>
                <div class="mdl-body">
                    <h3>Content modal</h3>
                </div>
                <div class="mdl-footer mdl-band-primary">
                    <button class="confirm" onclick="return false">Do
                    thing</button><button class="cancel" onclick=
                    "return false">Cancel the thing</button>
                </div>
            </center>
        </div>
    </div>
</body>
</html>

Код:

var myModal = {}

window.onload = function(){
  // It is one of the button Modalise will attach the Show event.
  // Note that you can use Modalise without the events, by omitting the .attach() function.
  // Then, you can use show() or hide() to use it manually without overload. 
  var btnOpen = document.getElementById('openModal');

  // Modalise(id, options);
  myModal = new Modalise('exampleModal', {
      btnsOpen : [btnOpen]
    })
    .attach()
    .on('onShow', console.log)
    .on('onConfirm', console.log)
    .on('onHide', console.log);
}

Ответ 5

Я создал библиотеку под названием Msg, которая упрощает создание модальных окон. В нем есть много вариантов и событий, чтобы создавать свои собственные виды модальных окон. Все можно настроить с помощью css. Это также один файл, нет необходимости импортировать файлы css.

Ответ 6

Использование position:fixed

и эту скрипту,

Мне удалось преодолеть ограничения первого ответа

Получение этой демонстрации. вам в основном нужен стек div с полноэкранным и фиксированным стилем положения и вложенным прокручиваемым содержимым div.

Вы также можете использовать document.write, а затем перенаправить, чтобы закрыть диалоговое окно.