Первоначальный план состоял в том, чтобы достичь такого требования: стойка регистрации запускает деловое действие, и пользователь должен дополнять информацию, не прыгая на страницу и информацию о дополнении в виде всплывающих окон. Это было обеспокоено, но в конце концов он не использовался.
Код по -прежнему немного вьющиеся и обеспечивает грубую логику реализации.
Идея реализации: положите маску на окно, чтобы заблокировать исходную кнопку функции окна, и реализуйте всплывающие окна в абсолютном позиционировании на верхнем слое маски. Взаимодействие данных в всплывающем окне является методом Ajax. Используйте Onclick, чтобы начать всплывающее событие.
Детали ключей: всплывающее окно и исходная форма-это по сути та же страница. Для удобства описания давайте назовем нижнюю форму родительской формы и всплывающее окно для детской формы. Чтобы достичь взаимодействия родительской формы, вам необходимо сделать некоторые специальные метки в родительской форме, чтобы селектор мог выбрать и вставить новый объект DOM.
Таким образом, сначала посмотрите на код родительской формы. У меня есть комментарии к ключевой части.
<html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta name = "Apple-mobile-web-app-capable" content = "yes"> <meta name = "Apple-mobile-web-app-status-bar-стиль" content = "black"> <title> тест всплывающее окно </title> <script type = "text/javascript" src = "script/jquery/jquery.js" type = "text/javascript" src = "script/js/outil.js" charset = "utf-8"> </script> <script charset = "utf-8" type = "text/javascript" src = "script/jquery/jquery.ui.js"> </script> <link rel rel = "lelshelet" type. "ui.js" href = "script/jquery/themes/ui-lightness/jquery.ui.css"> <script charset = "utf-8" type = "text/javascript" src = "script/dialog.js" id = "dialog_js"> </script> <link href = "script/dialogs. type = "text/css"> <style type = "text/css"> *{margin: 0; Заполнение: 0; Текст-альбом: Центр; Текстовое декорация: нет; } body {font: 12px/1,5 songyi, tahoma, arial, sans-serif; Фондовая семья: «Microsoft Yahei»; Ширина: 320px; Высота: Авто; Поле: 0 Авто; } .content {border: #ccc solid 1px; Маржа: 60px 10px 10px; Фон: #fff; переполнение: скрыто; Цвет:#6b6b6b; размер шрифта: 14px; граница радий: 5px; } </style> </head> <body> <!-Селектор выбирается ecttype = "dialog"-> <div> <a href = "javascript: void (0);" ecttype = "dialog" dialog_id = "dialog_test" dialog_title = "test Dialoge Test" dialog_width = "300" uri = "pop_son.html"> ДиалогЗатем дайте селекторную часть кода, то есть код Outil.js. Конечно, я не буду говорить о предыдущем интерфейсе jQuery и JQuery. По своей сути он обязан щелкнуть события.
jquery.extend ({getCookie: function (sname) {var acookie = document.cookie.split (";"); for (var i = 0; i <acookie.length; i ++) {var acrobume = acookie [i] .split ("="); if (sname == acrumb [0] returbumponer (1); }, SetCookie: Function (Sname, Svalue, Sexpires) {var scookie = sname + "=" + encodeuricomponent (svalue); истекает = пт, 31 декабря 1999 г. 23:59:59 gmt; ";}}); $ (function () { /*Диалог Выберите и связывает новое событие щелчка* / $ ('*[ectype =" dialog "]'). Click (function () {var id = $ (this) .attr ('dialog_id'); $ (this) .attr ('Dialog_title'): ''; = URL; }}/* Показать форму ajax*/function ajax_form (id, title, url, width) {if (! Width) {width = 400; } var d = dialogmanager.create (id); D.SetTitle (заголовок); D.SetContents ('Ajax', URL); D.SetWidth (ширина); D.show ('Center'); return d;} function go (url) {window.location = url;} function set_zindex (родители, index) {$. $ (n) .css ('z-index', index); var url = window.location.href; url = url.indexof ('#')> 0? url.replace (/#/g, ''): url; window.location.replace (url);} function js_fail (str) {$ ('#Warning'). html ('<<Cabel>' + str + '</label>'); $ ('#Warning'). Show ();} function check_pint (v) {var regu = /^[0-9] {1,} $ /; if (! regu.test (v)) {alert (lang.only_int); вернуть ложь; } return true;}/ * конвертировать & */function transform_char (str) {if (str.indexof ('&')) {str = str.replace (/&/g, "%26"); } return str;} // Копировать функцию буферизации copyToclipboard (txt) {if (window.clipboarddata) {window.clipboarddata.cleardata (); window.clipboarddata.setData ("text", txt); } else if (navigator.useragent.indexof ("opera")! = -1) {window.location = txt; } else if (window.netscape) {try {netscape.security.privilegemanager.enableprivilege ("UniversalxpConnect"); } catch (e) {return false; } var clip = components.classes ['@mozilla.org/widget/clipboard;1'5.createinstance(components.interfaces.nsiclipboard); if (! clip) вернуть false; var trans = components.classes ['@mozilla.org/widget/transferable;1'5.createinstance(components.interfaces.nsitransferable); if (! транс) вернуть ложь; Trans.Addataflav ('Text/Unicode'); var str = new Object (); var len = new Object (); var str = components.classes ["@mozilla.org/supports string;1"^.createinstance(components.interfaces.nsisupportsstring); var copyright = txt; str.data = copyText; trans.setTransferData ("text/unicode", str, copyText.length*2); var clipid = components.interfaces.nsiclipboard; if (! clip) вернуть false; clip.setData (trans, null, clipid.kglobalclipboard); }}Соответствующий код для событий привязки является основным кодом диалога (Dialog.js). Это было найдено в Интернете. Спасибо здесь. Код заключается в следующем:
__Dialog_wrapper__ = {};/* В IE6 есть ошибка. Если ширина диалогового окна не указана, диалоговое окно будет отображаться с 100% шириной в IE6*/Dialogmanager = {'create': function (id) {var d = {}; if (! __ dialog_wrapper __ [id]) {d = new Dialog (id); __Dialog_wrapper __ [id] = d; } else {d = dialogmanager.get (id); } return d; }, 'get': function (id) {return __dialog_wrapper __ [id]; }, 'close': function (id) {if (__dialog_wrapper __ [id] .close ()) {__dialog_wrapper __ [id] = null; }}, 'onclose': function () {return true; }, /* Load Dialog Style* / 'loadstyle': function () {var _dialog_js_path = $ ('#dialog_js'). Attr ('src'); var _path = _dialog_js_path.split ('/'); var _dialog_css = _path.slice (0, _path.length - 1) .join ('/') + '/dialog.css'; $ ('#dialog_js'). After ('<link href = "' + _dialog_css + '" rel = "styleSheet" type = "text /css" />'); }}; Screenlocker = {'style': {'position': 'absolute', 'top': '0px', 'left': '0px', 'founalcolor': '#000', 'непрозрачность': 0.5, 'zindex': 999}, 'masker': null, 'lock': function (zindex) {if whis.mask) this.masker.width ($ (документ) .width ()). Height ($ (Document) .height ()); вернуть истину; } this.masker = $ ('<div> </div>'); / * IE6 Hack */ if ($ .browser.msie) {$ ('select'). CSS ('Visiby', 'hidden'); } // var _iframe = $ ('<iframe> </iframe>'). CSS ({'opacity': 0, 'ширина': '100%', 'height': '100%'}); //this.masker.append(_IFRAME); /* Style*/ this.masker.css (this.style); if (zindex) {this.masker.css ('Zindex', Zindex); } /* Ширина и высота всего документа* / this.masker.width ($ (document) .width ()). Высота ($ (документ) .height ()); $ (document.body) .append (this.masker); }, 'разблокировать': function () {if (this.masker === null) {return true; } this.masker.remove (); this.masker = null; / * IE6 Hack */ if ($ .browser.msie) {$ ('select'). Css ('Visiby', 'visible'); }}}; Dialog = function (id) { / * Конструктор генерирует диалоговый код и добавляет его в документ * / this.id = id; this.init ();}; dialog.prototype = { / * Уникальный идентификатор * / 'id': null, / * объект документа * / 'dom': null, 'lastpos': null, 'status': 'overse', 'onclose': function () {return true; }, 'tmp': {}, /* инициализировать* / 'init': function () {this.dom = {'warper': null, 'body': null, 'head': null, 'title': null, 'close_button': null, 'content': null}; /* Создать внешний контейнер*/this.dom.wrapper = $ ('<div id = "dialog_object_' + this.id + '"> </div>'). Get (0); /* Создать тело диалога*/this.dom.body = $ ('<div> </div>'). Get (0); /* Создать строку заголовка*/this.dom.head = $ ('<h3> </h3>'). Get (0); /* Создать текст заголовка*/this.dom.title = $ ('<pan> </span>'). Get (0); /* Создать кнопку закрытия*///this.dom.close_button = $ ('<pan> close </span>'). Get (0); /* Создать область контента*/this.dom.content = $ ('<div> </div>'). Get (0); /* Создать область контента*/this.dom.content = $ ('<div> </div>'). Get (0); /* Комбинация*/$ (this.dom.head) .append ('<div> </div> <div> </div>'). Append ($ ('<pran> </span>'). Append (this.dom.title)). Append (this.dom.close_button); $ (this.dom.body) .append (this.dom.head) .append (this.dom.content); $ (this.dom.wrapper) .append (this.dom.body) .append ('<div style = "clear: оба; дисплей: block;"> </div>'); /* Стиль инициализации*/ $ (this.dom.wrapper) .css ({'Zindex': 9999, 'Display': 'none', 'position': 'Absolute'}); $ (this.dom.body) .css ({'position': 'относительно'}); $ (this.dom.head) .css ({'cursor': 'Move'}); $ (this.dom.close_button) .css ({'position': 'absolute', 'text-indent': '-9999px', 'cursor': 'pointer', 'overflow': 'hidden'}); $ (this.dom.content) .css ({'margin': '0px', 'padding': '0px'}); var self = это; /* Инициализировать событие компонента*/ $ (this.dom.close_button) .click (function () {dialogmanager.close (self.id);}); / * Перетаскивать */ $ (this.dom.wrapper) .daggable ({'handle': this.dom.head}); /* Поместить в потоку документов*/ $ (document.body) .append (this.dom.wrapper); }, /* Скрыть* / 'hide': function () {$ (this.dom.wrapper) .hide (); }, / * Show * / 'show': function (pos) {if (pos) {this.setposition (pos); } /* ЗАКЛЮЧЕНИЕ ЗАКЛЮЧЕНИЕ* / Screenlocker.lock (999); /* Показать диалог*/ $ (this.dom.wrapper) .show (); }, /* Close* / 'close': function () {if (! This.onclose ()) {return false; } /* Close Dialog* / $ (this.dom.wrapper) .Remove (); /* Разблокировать экран*/ screenlocker.unlock (); вернуть истину; }, /* Название диалога* / 'settitle': function (title) {$ (this.dom.title) .html (title); }, /* Изменить содержимое диалогового окна* / 'setContents': function (type, options) {contents = this.createContents (type, options); if (typeof (contents) == 'string') {$ (this.dom.content) .html (contents); } else {$ (this.dom.content) .empty (); $ (this.dom.content) .append (содержание); }}, /* Установить стиль диалогового окна* / 'setStyle': function (style) {if (typeof (style) == 'Object') { /* В противном случае это css* / $ (this.dom.wrapper) .css (style); } else { / * Если это строка, это считается названием стиля * / $ (this.dom.wrapper) .addclass (style); }}, 'setwidth': function (width) {this.setStyle ({'width': width + 'px'}); }, 'setheight': function (height) {this.setStyle ({'height': height + 'px'}); }, /* Сгенерировать содержимое диалога* / 'createContents': function (type, options) {var _html = '', self = this, status = 'complete'; if (! options) { / * Если есть только один параметр, он считается html string * / this.setStatus (status); возврат типа; } switch (type) {case 'ajax': /* Получить html через Ajax и отобразить его на странице. Этот процесс является асинхронным*/ $ .get (options, {ajax: 1}, function (data) {if (data.substr (0,1) == '{' && data.substr (data.length - 1, 1) == '}') {var json = eval (' + data +'); if (! return; 'close') {self.close (); / * Сначала подскажите, что он загружается */ _html = this.createContents ('загрузка', {'text': 'загрузка ...'}); перерыв; /* Ниже приведены несколько встроенных типов диалогов*/case 'загрузка': _html = '<div> <div>' + options.text + '</div> </div>'; status = 'загрузка'; перерыв; case 'message': var type = 'note'; if (options.type) {type = options.type; } _message_body = $ ('<div> </div>'); _message_contents = $ ('<div>' + options.text + '</div>'); _buttons_bar = $ ('<div> </div>'); Switch (type) {case 'vement': case 'Warning': var button_name = lang.confirm; if (options.button_name) {button_name = options.button_name; } _ok_button = $ ('<input type = "button" value = "' + button_name + '" />'); $ (_ ok_button) .click (function () {if (options.onclick) {if (! options.onclick.call ()) {return;}} dialogmanager.close (self.id);}); $ (_ bultons_bar) .append (_ok_button); перерыв; case 'Подтверждение': var yes_button_name = lang.yes; var no_button_name = lang.no; if (options.yes_button_name) {yes_button_name = options.yes_button_name; } if (options.no_button_name) {no_button_name = options.no_button_name; } _yes_button = $ ('<<input type = "button" value = "' + yes_button_name + '" />'); _no_button = $ ('<<input type = "button" value = "' + no_button_name + '" />'); $ (_ yes_button) .click (function () {if (options.onclickyes) {if (options.onclickyes.call () === false) {return;}} dialogmanager.close (self.id);}); $ (_ no_button) .click (function () {if (options.onclickno) {if (options.onclickno) {if (! options.onclickno.call ()) {return;}} dialogmanager.close (self.id);}); $ (_ buttons_bar) .append (_yes_button) .append (_no_button); перерыв; } _html = $ (_ message_body) .append (_message_contents) .append (_buttons_bar); перерыв; } this.setStatus (status); вернуть _html; }, /* Position* / 'setPosition': function (pos) { /* Последняя позиция* / this.lastpos = pos; if (typeof (pos) == 'string') {switch (pos) {case 'center': var left = 0; var top = 0; var dialog_width = $ (this.dom.wrapper) .width (); var dialog_height = $ (this.dom.wrapper) .height (); / * слева = ширина прокрутки + (текущая область просмотра - ширина диалогового окна) / 2 * / left = $ (window) .scrollleft () + ($ (window) .width () - dialog_width) / 2; / * top = высота прокрутки + (текущая область просмотра - высота диалогового окна) / 2 * / top = $ (window) .scrolltop () + ($ (window) .height () - dialog_height) / 2; $ (this.dom.wrapper) .css ({слева: слева + 'px', top: top + 'px'}); перерыв; }} else {var _pos = {}; if (typeof (pos.left)! = 'undefined') {_pos.left = pos.left; } if (typeof (pos.top)! = 'undefined') {_pos.top = pos.top; } $ (this.dom.wrapper) .css (_pos); }}, /* Set status* / 'setStatus': function (code) {this.status = code; }, /* Получить статус* / 'getStatus': function () {return this.status; }, 'disableclose': function (msg) {this.tmp ['oldonclose'] = this.onclose; this.onclose = function () {if (msg) alert (msg); вернуть ложь; }; }, 'enableclose': function () {this.onclose = this.tmp ['oldonclose']; this.tmp ['oldonclose'] = null; }}; // removeByzzy20160909: вручную ввести файл стиля //dialogmanager.loadstyle ();ОК, вышеуказанное - основная логика и реализация кода. Код хорошо объясняет весь процесс, и нет необходимости тратить текст. Я опубликую здесь подчиненную.
<style> .btn {margin: 10px 5px; Ширина: 100px; } </style> <form method = "post" action = "{$ myAction}" id = "popupform"> <div style = "margin-top: 10px;" > <p> отображаемое здесь содержимое может быть формой или не формой. <input type = "hidden" name = "ret_url" value = "{$ ret_url}"/> </p> <input type = "Отправить" value = "complete"/> </div> </form>Наконец, я опубликую еще один рендеринг.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.