Introduction to encapsulation examples of js custom bullet box plug-in
First, let’s sort out our thoughts. Native javascript actually implements the alert() method, but that will temporarily interrupt the running of the program and is enough to make you ugly! So put aside these and think about it carefully, in fact, the pop-up frame is two p-layers, and a masking layer (mask layer) floating underneath, covering all elements, and it is best to be translucent. The other is the main part of the pop-up box. Generally, it needs to be centered horizontally and vertically, and usually contains a title. The main content needs to be customizable. If it is a modal box, there is usually a confirm/cancel button. Finally, there are some animation effects when popping up and closing.
Pop-up layer prompt information, this is the most common requirement in mobile front-end development. You may think of some popular pop-up box plug-ins, such as the classic artDialog, the cool Sweetalert, etc..
But slowly you will find that customization requirements are usually higher. General pop-up plug-ins may only meet most of the requirements. Customization is not as time-consuming as manually encapsulating one that suits your own development habits. Pop-up component, so that subsequent development efficiency will be greatly improved.
So you can encapsulate one yourself and put it in the public js in the project. If you can write it yourself, try not to use plug-ins....
Some default attribute values
pass through a foreach loop, similar to the incoming opts Inheriting the defaultOpts attribute, the before() method executed before calling the pop-up box is equivalent to some preparation work
var defaultOpts = { title: '',//标题 content: '',//内容 文字 || html height: 50,//默认屏幕(父级)的50% width: 80,//默认屏幕(父级)的80% type: 'alert-default',//弹框类型 effect: 'fadeIn',//出现效果,默认下跌落 delayTime: 500,//效果延时时间,默认.5s autoClose: false,//自动关闭 autoTime: 2000, //自动关闭时间默认2s autoEffect: 'default',//关闭效果 ok: '确定', okCallback: function(){},//确定回调 cancel: '取消', cancelCallback: function(){},//取消回调 before : function() { console.log('before') }, close: function() { console.log('close') }, blankclose: false//空白处点击关闭 } for (i in defaultOpts) { if (opts[i] === undefined) { opts[i] = defaultOpts[i] } } opts.before && opts.before()
dom structure
definition An array object, which contains the DOM element of the pop-up box. alert-mask is the full-screen mask layer, and alert-content is the main content area of the pop-up box. Finally, the array is converted to html through the .join('') function, and then used The append() method of jquery is appended to the end of the body node.
var alertHtml = [ '<section class="alert-main" id="alertMain">', '<p class="alert-mask li-opacity" id="alertMask"></p>', '<p class="alert-content '+ opts.type +'" id="alertContent">', opts.content +'</p>', '</section>' ] $('body').append(alertHtml.join(''))
Set the height and width, horizontally and vertically centered
I use fixed positioning here, and height is the height passed in (Percentage), the distance between top and the top of the screen is 100-the incoming height/2. This achieves vertical centering, and the same goes for the width. This method of horizontal and vertical centering is also what I think is the simplest and most practical after long-term practice. It is compatible with various screen sizes. Of course, there are many methods, you can try it yourself
##
var $alertContent = $('#alertContent'), $alertMain = $('#alertMain'); $alertContent.css({ 'height': opts.height + '%', 'top': (100 - opts.height)/2 + '%', 'width': opts.width + '%', 'left': (100 - opts.width)/2 + '%' }) $('.li-opacity').css({ '-webkit-animation-duration' : opts.delayTime/1000 + 's' })The last sentence is to assign an animation execution time to the mask layer to achieve the fade-in effect. For details, see the CSS below @-webkit-keyframes opacity
Bomb frame effect
I have implemented four effects here, namely fadeIn falling and sideLeft flying from the left Enter, scale amplification, and info prompt information. As you can see, I defined a collection object, placed the corresponding css attributes respectively, and then assigned values uniformly through two setTimeout functionsvar effect = { 'fadeIn': 'top', 'fadeInStart': '-100%', 'fadeInValue': (100 - opts.height)/2 + '%', 'sideLeft': 'left', 'sideLeftStart': '-100%', 'sideLeftValue': (100 - opts.width)/2 + '%', 'scale': '-webkit-transform', 'scaleStart': 'scale(0)', 'scaleValue': 'scale(1)', 'info': '-webkit-transform', 'infoStart': 'scale(1.2)', 'infoValue': 'scale(1)' } setTimeout(function(){ $alertContent.css(effect[opts.effect],effect[opts.effect + 'Start']).addClass('alert-show') setTimeout(function(){ $alertContent.css(effect[opts.effect], effect[opts.effect + 'Value']) opts.close && opts.close() },10) },opts.delayTime)
Click on the blank space Close
Usually the requirement is to click on the blank space of the pop-up box to close the pop-up box. This can be done with a click event. The focus is on the previous selector. jquery has given us so much convenience... . Of course, in the end, in order to prevent clicking on other elements of the page and prevent events from bubbling up, the default behavior of the component is...if(opts.blankclose) { $('.alert-main :not(.alert-content)').on('click',function(event){ $alertMain.remove() opts.close && opts.close() event.stopPropagation() event.preventDefault() }) }
Automatically close
When autoClose is true and autoTime is greater than zero, use a delay event to automatically close the pop-up boxif(opts.autoClose && opts.autoTime > 0) { setTimeout(function(){$alertMain.remove()},opts.autoTime) opts.close && opts.close() }
Demo:
css@-webkit-keyframes opacity { 0% { opacity: 0; /*初始状态 透明度为0*/ } 50% { opacity: 0; /*中间状态 透明度为0*/ } 100% { opacity: 1; /*结尾状态 透明度为1*/ } } .li-opacity { -webkit-animation-name: opacity; /*动画名称*/ -webkit-animation-iteration-count: 1; /*动画次数*/ -webkit-animation-delay: 0s; /*延迟时间*/ } .alert-mask { position: fixed; height: 100%; width: 100%; left: 0%; top: 0%; z-index: 9998; background-color: rgba(0,0,0,.7); } .alert-content { position: fixed; box-sizing: border-box; border-radius: 4px; z-index: 9999; -webkit-transition: .4s; -moz-transition: .4s; transition: .4s; display: none; } .alert-show { display: block; } .alert-default { background-color: white; }html
<p class="alert" data-flag="fadeIn">fadeIn</p> <p class="alert" data-flag="sideLeft">sideLeft</p> <p class="alert" data-flag="scale">scale</p> <p class="alert" data-flag="info">info</p>js
require.config({ jquery:'component/jquery/jquery-3.1.0.min', liAlert: 'li/li-alert',//常用弹框组件 }) require(['jquery'],function($){ require(['liAlert'],function(){ $('.alert').on('click',function(event){ $.alert({ content: '<h1 id="我是弹框">我是弹框</h1>', effect: $(event.currentTarget).attr('data-flag'), blankclose: true, //autoClose: true }) }) }) })Rendering
The above is the detailed content of Introduction to encapsulation examples of js custom bullet box plug-in. For more information, please follow other related articles on the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)