Bootstrap modal window source code analysis

Source: Internet
Author: User
This article mainly gives you a detailed explanation of the Bootstrap modal window source code, and adds comments to each basic line, which has some reference value. If you are interested, you can refer Preface:

The source code of the js plug-in of bootstrap is very well written. It is also an exemplary way of writing the jquery plug-in. I still want to give a detailed analysis. Alas, there is no time, I have read the source code a long time ago and have posted it on my blog,

There are many advanced usage of jquery in the code line 300. We recommend that you download the source code from github, copy the code in this article, and then run and read it, if you have any questions, you can leave a message for me to answer.

The following is a comment on each basic line for your reference. The specific content is as follows:

/* ===================================================== ====================================== * Bootstrap: modal. js v3.3.7 * # * ====================================== ================================================================= * Copyright 2011 -2016 Twitter, inc. * Licensed under MIT (#) * ===================================================== ======================================= */+ function ($) {'use strict '; // modal class definition // ========================== = Var Modal = function (element, options) {// modal class: first, the Modal constructor declares the variables to be used, and then sets some constants. This. options = options this. $ body = $ (document. body) this. $ element = $ (element) this. $ dialog = this. $ element. find ('. modal-dialog ') this. $ backdrop = null this. isShown = null this. originalBodyPad = null this. scrollbarWidth = 0 this. ignoreBackdropClick = false // ignore whether the mask is clicked. if (this. options. remote) {// this is the case of remote call data. Use the remote template to fill the modal box this. $ element. find ('. modal-content '). load (this. options. remote, $. Proxy (function () {this. $ element. trigger ('loaded. bs. modal') // triggers the listener function when data is loaded}, this)} modal. VERSION = '3. 3.7 'modal. TRANSITION_DURATION = 300 // transition duration over time Modal. BACKDROP_TRANSITION_DURATION = 150 // specifies the background excessive time (Modal. DEFAULTS = {// default value of defaults: backdrop: true, // whether there is a mask layer keyboard: true, // when the esc key on the keyboard is pressed, the modal box is closed. Show: true // The modal box is displayed immediately after initialization.} // After the variable is set, the function is ready. Modal extensions include: // toggel, show, hide, enforceFocus, escape, resize, hideModal, removeBackdrop, // backdrop, handleUpdate, adjustDialog, callback, checkScrollbar, setScrollbar, resetScrollbar, // measureScrollbar finally has 16 columns in total. The toggel function is relatively simple. It is a display and hidden switching function. The Code is as follows: Modal. prototype. toggle = function (_ relatedTarget) {return this. isShown? This. hide (): this. show (_ relatedTarget)} Modal. prototype. show = function (_ relatedTarget) {var that = this var e = $. event ('Show. bs. modal', {relatedTarget: _ relatedTarget}) // triggers the show. bs. modal event, and assign $ to relatedTarget. the purpose of Event creation is to assign this to an Event object. $ element. trigger (e) // if (this. isShown | e. isDefaultPrevented () return // if it is already displayed, this is returned. isShown = true // mark this. checkScrollbar () // check whether there is a scroll bar and measure the scroll bar Width (non-X axis) this. setScrollbar () // If a scroll bar exists, a padding-right is given to the body to indicate the width of the scroll bar. The purpose of this step is to echo this. Remove the y-axis scroll bar below this. $ body. addClass ('modal-open') // Add the modal-open class to the body element, that is, remove the y-axis scroll bar, and the page will be a scroll bar width to the right, this. escape () // Press esc to exit the mode this. resize () // adjust the window size, change the window size, and change the modal box as well. $ element. on ('click. dismiss. bs. modal', '[data-dismiss = "modal"]', $. proxy (this. hide, this) // register the Close event this in the upper right corner. $ dialog. on ('mousedown. dismiss. bs. modal', function (){ // Press the mouse in the dialog and raise the mouse in the parent element. Ignore: press the mouse in the modal mode and hold the mouse in the mask layer. $ element. one ('mouseup. dismiss. bs. modal', function (e) {// lift if ((e.tar get) in the parent element ). is (that. $ element) that. ignoreBackdropClick = true}) this. backdrop (function () {// mask layer: It is really a pressure axis function, and, this callback function is the function var transition =$. support. transition & that. $ element. hasClass ('fade ') if (! That. $ element. parent (). length) {that. $ element. appendTo (that. $ body) // don't move modals dom position} that. $ element. show (). scrollTop (0) // show and get the top that. adjustDialog () // adjust the dialog box if (transition) {that. $ element [0]. offsetWidth // force reflow} that. $ element. addClass ('in') that. enforceFocus () var e = $. event ('shown. bs. modal', {relatedTarget: _ relatedTarget}) transition? That. $ dialog // wait for modal to slide in. one ('bstransitionend', function () {that. $ element. trigger ('focal '). trigger (e) // trigger foucus and shown after the mode is too high. bs. modal }). emulateTransitionEnd (Modal. TRANSITION_DURATION): that. $ element. trigger ('focal '). trigger (e) // otherwise proceed directly})} Modal. prototype. hide = function (e) {// its existence is an event listening function, so you can add e. below is the modal window to close the processing function if (e) e. preventDefault () // cancel default behavior e = $. event ('hide. bs. moda L ') // whatever event is entered here, it is changed to 'hide. bs. modal is universal in this way, whether it is to click "x", or cancel, OK, it is handled like this. $ element. trigger (e) // issue hide if (! This. isShown | e. isDefaultPrevented () return this. isShown = false // restore the initial false this. escape () // remove the esc event this. resize () // remove the resize event bound to the window $ (document ). off ('focusin. bs. modal') // this. $ element. removeClass ('in '). off ('click. dismiss. bs. modal '). off ('mouseup. dismiss. bs. modal') this. $ dialog. off ('mousedown. dismiss. bs. modal') // all removed $. support. transition & this. $ element. hasClass ('fade ')? This. $ element. one ('bstransitionend', $. proxy (this. hideModal, this) // here, although the mode is no longer available, the transparency is changed to 0, this. hideModal is actually removed. emulateTransitionEnd (Modal. TRANSITION_DURATION): this. hideModal ()} Modal. prototype. enforceFocus = function () {// The modal box gets the focus $ (document ). off ('focusin. bs. modal') // guard against infinite focus loop. on ('focusin. bs. modal', $. proxy (function (e) {if (document! = E.tar get & this. $ element [0]! = E.tar get &&! This.w.element.has(e.tar get ). length) {this. $ element. trigger ('focal ') }}, this)} Modal. prototype. escape = function () {// when the esc key on the keyboard is pressed, the modal box is closed. If (this. isShown & this. options. keyboard) {// this event is registered only when the modal window is displayed. $ element. on ('keydown. dismiss. bs. modal', $. proxy (function (e) {// not only can pass through the event ,... Niu e. which = 27 & this. hide () // 27 call the hide method (ps: much easier than if, Master is a master)}, this)} else if (! This. isShown) {// otherwise, it feels strange to remove it. No matter this. $ element. off ('keydown. dismiss. bs. modal')} modal. prototype. resize = function () {// register the event if (this. isShown) {$ (window ). on ('resize. bs. modal', $. proxy (this. handleUpdate, this)} else {$ (window ). off ('resize. bs. modal')} modal. prototype. hideModal = function () {var that = this. $ element. hide () this. backdrop (function () {that. $ body. removeCl Ass ('modal-open') that. resetAdjustments () that. resetScrollbar () that. $ element. trigger ('den den. bs. modal')} modal. prototype. removeBackdrop = function () {this. $ backdrop & this. $ backdrop. remove () this. $ backdrop = null} Modal. prototype. backdrop = function (callback) {var that = this var animate = this. $ element. hasClass ('fade ')? 'Fade ': ''// whether fade animation class if (this. isShown & this. options. backdrop) {// condition: show is in progress and there is a mask layer var doAnimate =$. support. transition & animate // do must support over-css3 and fade class this. $ backdrop = $ (document. createElement ('P') // create the mask layer p. addClass ('modal-backdrop' + animate) // Add modal-backdrop and fade class. appendTo (this. $ body) // Add it to the bottom of the body (to be determined, other versions may be added to the modal) this. $ element. on ('click. dismiss. bs. modal', $. proxy (function (E) {// click the modal window to process the event: if (this. ignoreBackdropClick) {this. ignoreBackdropClick = false return} if (e.tar get! = E. currentTarget) return // If the mode is not clicked, this. options. backdrop = 'static '? This. $ element [0]. focus () // specify the static background, click: this. hide () // otherwise close the mode}, this) if (doAnimate) this. $ backdrop [0]. offsetWidth // force reflow. $ backdrop. addClass ('in') // Add the transparency of in 0.5 if (! Callback) return doAnimate? This. $ backdrop. one ('bstransitionend', callback ). emulateTransitionEnd (Modal. BACKDROP_TRANSITION_DURATION): // if there is a fade animation, bind an excessive mask time to the mask layer. Why do you need to write this? Call back ()} else if (! This. isShown & this. $ backdrop) {this. $ backdrop. removeClass ('in') var callbackRemove = function () {that. removeBackdrop () callback & callback ()} $. support. transition & this. $ element. hasClass ('fade ')? This. $ backdrop. one ('bstrancetionend', callbackRemove ). emulateTransitionEnd (Modal. BACKDROP_TRANSITION_DURATION): callbackRemove ()} else if (callback) {callback () }}// these following methods are used to handle overflowing modals Modal. prototype. handleUpdate = function () {this. adjustDialog ()} Modal. prototype. adjustDialog = function () {// handle the modal location discord problem caused by the scroll bar var modalIsOverflowing = this. $ e Lement [0]. scrollHeight> document.doc umentElement. clientHeight // whether the mode overflows the screen, that is, the height is greater than the client height this.w.element.css ({paddingLeft :! This. bodyIsOverflowing & modalIsOverflowing? This. scrollbarWidth: '', paddingRight: this. bodyIsOverflowing &&! ModalIsOverflowing? This. scrollbarWidth: ''})} Modal. prototype. resetAdjustments = function () {this.$element.css ({paddingLeft: '', paddingRight:''})} Modal. prototype. checkScrollbar = function () {var full1_wwidth = window. innerWidth if (! Full1_wwidth) {// workaround for missing window. innerWidth in IE8 var documentElementRect = document.doc umentElement. getBoundingClientRect () full1_wwidth = documentElementRect. right-Math. abs (documentElementRect. left)} this. bodyIsOverflowing = document. body. clientWidth <full1_wwidth // whether a scroll bar exists this. scrollbarWidth = this. measureScrollbar ()} Modal. prototype. setScrollbar = function () {// use To set the value of padding-right for the body element to prevent the body element from being blocked by scrollbar var bodyPad = parseint(this.?body.css ('padding-right') | 0), 10) this. originalBodyPad = document. body. style. paddingRight | ''if (this. bodyIsOverflowing) this.$body.css ('padding-right', bodyPad + this. scrollbarWidth)} Modal. prototype. resetScrollbar = function () {this.$body.css ('padding-right', this. originalBodyPad)} Modal. prototype. measureScro Llbar = function () {// thx orthogonal measurement Scrollbar var scrollp = document. createElement ('P') scrollp. className = 'modal-scrollbar-measure 'this. $ body. append (scrollp) var scrollbarWidth = scrollp. offsetWidth-scrollp. clientWidth this. $ body [0]. removeChild (scrollp) return scrollbarWidth} // modal plugin definition // ==================================== function Plugin (option, _ relatedTarget) {return this. each (fu Nction () {var $ this = $ (this) var data = $ this. data ('bs. modal') // If the modal window is opened for the second time, this data will have var options = $. extend ({}, Modal. DEFAULTS, $ this. data (), typeof option = 'object' & option) // merge the default parameters. // if (! Data) $ this. data ('bs. modal', (data = new modal (this, options) // Save the Modal object to avoid the new object when it is opened for the second time, it is worth learning that if (typeof option = 'string') data [option] (_ relatedTarget)/* the difference here is that option is an object and a string */else if (options. show) data. show (_ relatedTarget)} var old = $. fn. modal $. fn. modal = Plugin $. fn. modal. constructor = Modal // modal no conflict // =========================$. fn. modal. noConflict = function () {$. fn. modal = Old return this} // MODAL DATA-API here is the key to implementing modal without a line of js Code). on ('click. bs. modal. data-api ',' [data-toggle = "modal"] ', function (e) {// trigger the modal box when you click the button, var $ this = $ (this) var href = $ this. attr ('href ') var $ target = $ ($ this. attr ('data-target') | (href & href. replace (/. *(? = # [^ \ S] + $)/, '') // strip for ie7 var option = $ target. data ('bs. modal ')? 'Toggle ': $. extend ({remote :! /#/. Test (href) & href}, $ target. data (), $ this. data () // this is the difference between the first trigger and the second trigger // so far to get the controlled modal dom element if ($ this. is ('A') e. preventDefault () $ target. one ('Show. bs. modal', function (showEvent) {// if (showEvent. isdefapreprevented () return // only register focus restorer if modal will actually get shown $ target. one ('ddden. bs. modal', function () {// events created after show is called, triggered after the modal box is hidden, $ this. is (': visible') & $ this. trigger ('focal ') // if the original button still exists (or is displayed), let it get the focus}) Plugin. call ($ target, option, this)} (jQuery );

The above is all the content of this article. I hope it will help you learn and support PHP.

For more articles about Bootstrap modal window source code parsing, refer to PHP Chinese network!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.