search
HomeWeb Front-endJS TutorialJquery implements pop-up layer plug-in_jquery

There are still many applications for pop-up layers, such as login and some operations on the same page. Others' belongings belong to others, and your own belongs to you, so I have always wanted to write a pop-up layer plug-in. Without further ado, let’s get started!

1: Mask layer

To pop up a layer, you must first use a mask layer to block the page below. This mask layer is full screen and the page needs to scroll, so set position: fixed; it also has a transparency effect. Here is my definition The mask layer css is named mask

Copy code The code is as follows:

.mask
{
position: fixed;
width: 100%;
height: 100%;
background-color: white;
Overflow: scroll;
Filter: alpha(opacity=50);
-moz-opacity: 0.5;
Opacity: 0.5;
z-index: 20;
Overflow: auto;
top: 0px;
Right: 0px;
}

2: Main parameters of the plug-in

tag: Why do you need tag? You can use tags to specify hidden elements that need to be popped up. You can specify tags as the selector "#*", so that the specified elements can be popped up. Here I set the default to this.

mainContent: Is this parameter required? I don't think it's very useful. I set it mainly for server controls. If all are added to the body, the form cannot be submitted. But after clicking submit, the page will refresh and the pop-up layer disappears, so I think it is still useless...

Copy code The code is as follows:

$.fn.xsPop = function (options) {
        var defaults = {//Default value
              title: "Pop-up window", //Window title
                width: 500,
Heigth: 400,
             tag: this, //Pop up the elements that need to be loaded
              close: "Close",
                 mainContent: "body"//Container, in order to submit the form, but submit will refresh the page...
        };
         var options = $.extend(defaults, options); //Override with passed parameters
This.each(function () {
                     xsMain(options.title, options.width, options.heigth, options.tag, options.close, options.mainContent); //The main entrance of the plug-in
        });
};

3: Use the xsMain function to add elements and bind events

There is a process here, which is to control the height and width. If the setting exceeds the screen height and width, it will adapt to the screen, thus preventing the pop-up layer from being too large to operate. The other is to add html normally, I use string addition

Copy code The code is as follows:

//According to the incoming data, add a mask layer and pop up a prompt box
Function xsMain(title, width, height, tag, close, mainContent) {
      var divmask = "
";
​​​​ $(mainContent).append(divmask);
          var xsPop1 = " ";
      var allHtml = xsPop1 xsPop2 xsPop3 xsPop5;
​​​​ $(mainContent).append(allHtml);
​​​​ $(tag).show();
​​​​ $(tag).appendTo("#xsPopMain");
//Get the height and width of the browser and make subsequent judgments (height exceeds, dragging border limit)
clientHeight = window.screen.height;
clientWidth = window.screen.width;
If (height > clientHeight) {
             height = clientHeight - 100;
}
If (width > clientWidth) {
               width = clientWidth - 100;
}
           $("#xsPop").css({
"heigth": height "px",
"width": width "px",
"margin-top": "-" (height / 2) "px",
"margin-left": "-" (width / 2) "px"
        });
          $("#xsPopMain").css("height", height - $("#xsPopHead").height());
           xsdrag("#xsPopHead", "#xsPop"); //Bind drag action
             $("#xsColse").bind("click", function () { ClosePop(tag, mainContent); }); //Bind close action
}

4: Close action

Here you need to give the tag to the container first, otherwise it will be removed together when you remove it later, and the tag will not be found the second time it pops up.

Copy code The code is as follows:
//Close the popup layer
Function ClosePop(tag, mainContent) {
​​​​ $(mainContent).append(tag); //Save, otherwise $("#xsPop").remove() in step 4 will clear the tag
          $(tag).hide();
          $(".mask").remove();
          $("#xsPop").remove();
}

5: Drag effect

Method 1: The first time I find it is an event that uses elements, but it is easy to lose elements and the effect is not ideal

Copy code The code is as follows:

//Drag and drop the pop-up layer (failed method, object loss will occur)
//Control is the drag element, tag is the action element, generally the control is within the tag
// function drag(control, tag) {
// // var isMove = false;
// var abs_x = 0, abs_y = 0;
// // $(control).mousedown(
// // function (event) {
// // var top = $(tag).offset().top;
// // var left = $(tag).offset().left;
//                          abs_x = event.pageX - left;
// //                   abs_y = event.pageY - top;
// // isMove = true;
                                }).mouseleave(function () {
// // isMove = false;
// // });
// // $(control).mouseup(function () {
// // isMove = false;
// // });
// // $(document).mousemove(function (event) {
// // if (isMove) {
// // $(tag).css({
// // 'left': event.pageX - abs_x $(tag).width() / 2 - 1,
// // 'top': event.pageY - abs_y $(tag).height() / 2 - 1
// // // // }
// // return false;
// // });
// }

Method 2, the method I currently use, uses the down and up of the document, but there are still some problems, the problem of moving too fast, and the coordinates have a small jump

I also found a problem. If I drag the pop-up layer directly to the top of the screen and let go, haha, you will never be able to drag it back or click to close it. I took a look at the pop-up layer on Baidu's homepage. They also have this phenomenon, but after zooming in and out of the window, the pop-up layer will return to the center. I also tried to do this, but when I bound onresize, it appeared that it could not move to the bottom. The event they used was definitely not onresize. So I directly judged that the mouse position cannot be less than 0.

Copy code The code is as follows:

//Drag and drop pop-up layer
//Control is the drag element, tag is the action element, generally the control is within the tag
Function xsdrag(control, tag) {
           $(control).mousedown(function (e)//emouse event
            {
               var offset = $(this).offset(); //The position of DIV on the page
                 var x = e.pageX - offset.left; //Get the distance between the mouse pointer and the left border of the DIV element
                 var y = e.pageY - offset.top; //Get the distance between the mouse pointer and the upper boundary of the DIV element
$(document).bind("mousemove", function (ev)//Bind the mouse movement event, because the cursor must also have an effect outside the DIV element, so the document event must be used instead of the DIV element event
                {
If (EV.Pagey & Lt; = 0) {Return;} // Prevent the frame from being unable to close and drag
                     $(tag).css({
                    'left': ev.pageX - x $(tag).width() / 2, // I need to add this to my layout
‘top’: ev.pageY - y $(tag).height() / 2
                });
            });
        });
$(document).mouseup(function () {
               $(this).unbind("mousemove");
        });
}

6: Style sheet

The layout of the pop-up layer uses top and left margin-top negative values, so I add half of the height and width in my js

Copy code The code is as follows:

.mask
{
position: fixed;
width: 100%;
height: 100%;
background-color: white;
Overflow: scroll;
Filter: alpha(opacity=50);
-moz-opacity: 0.5;
Opacity: 0.5;
z-index: 20;
Overflow: auto;
top: 0px;
Right: 0px;
}
.PopUp
{
Padding: 0px;
Position: absolute;
z-index: 21 !important;
Background-color: White;
Border-style: solid solid solid solid;
Border-width: 1px;
Border-color: #C0C0C0;
Left: 50%;
top: 50%;
}
.PopHead
{
Background-color: #F0F0F0;
Border-bottom-style: solid;
Border-bottom-width: 1px;
Border-bottom-color: #C0C0C0;
Height: 30px;
Cursor: move;
clip: rect(0px, auto, auto, 0px);
}
.PopHead b
{
float: left;
Display: block;
Color: #C0C0C0;
font-family: System;
font-size: medium;
Line-height: 30px;
text-indent: 2em;
}
.PopHead span
{
float: right;
Display: block;
Text-align: right;
Line-height: 30px;
Cursor: pointer;
Text-indent: 5px;
Color: #FF0000;
font-size: 12pt;
}
.PopMain
{
Padding: 10px;
Overflow: auto;
}

7: Use of pages

Test server controls can submit forms

Copy code The code is as follows:

           $(document).ready(function () {
                $("#btnPop").click(function () {
              var options = {
                       title: "my pop",
                          width: 500,
Heigth: 400,
                                      close: "close",
                            mainContent: "form"
                }
                   $("#pop1").xsPop(options);
            });
        });

Okay, that’s it. I originally wanted to make a border pull to change the size, but found that it would take some time, so I stopped doing it. In fact, to be honest, I think dragging doesn't make much sense, and border control size doesn't make much sense either, because I set the overflow and scroll bars will appear.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools