Let's talk about the pop-up window.

Source: Internet
Author: User
Let's talk about the pop-up window.

A long time ago, I wrote an article about jquery's simple pop-up window function and published it to my favorite boiled fish. Very basic, very simple, some of the practices in it are immature, you can only say that simple implementation of such a pop-up window effect.

Although the writing is very basic, from the statistics, there are still a lot of people searching for this article. After more than a year, I have done the pop-up window function many times, I have a further understanding of the simple pop-up window effect, and I will summarize a more in-depth article.

Implementation Principle and Method of pop-up window

A pop-up window is usually composed of two parts: a translucent background mask and an area that carries the body content. When a button is clicked or triggered somewhere, the hidden masks and content are displayed through a certain animation effect. Then, click "off" or "mask area" in the content to hide the mask and content through a certain animation effect.

Therefore, the first step to pop-up is to write the structure and CSS.

The HTML structure and CSS of the pop-up window

Since the implementation method is known, the general structure mainly includes the following two types (used in minutes ):

First, separate the content block and declare a. Overlay Structure for background mask. The structure is as follows:

<div class="box-login">    ...</div><div class="overlay"></div>

In this way, you can. overlay Structure to set a translucent background image or use the rgba background, and then. the Layout mode of the box-login application is absolutely centered or the width and height or location are dynamically calculated using Js. (Of course, this method is compatible with IE8 +. You can use js to calculate the location and use a translucent GIF image as the background ).

The advantage of this structure is that the mask layer can be reused. In any scenario that requires pop-up windows, you can directly use the overlay mask layer and Twitter. This is also recommended.

For specific code, see the following demo using jsfiddle.


Second, wrap the content block into the. Overlay Structure. The structure is as follows:

<div class="overlay box-login">    <div class="section">        ...    </div></div>

This structure is more independent from other structures. It is relatively simple to control using JS, and it is more convenient to generate using JS and Other plug-ins. Fancybox generates this structure to implement pop-up windows.

However, it should be noted that because the content block is enclosed in the overlay layer, you must click the overlay layer to cancel the pop-up window, you need to prevent click or other event-related bubbles in the content block so that operations in the content block will not trigger the effect of canceling the pop-up window.

The specific code is as follows, or open the demo


Usually, a "close" button is added to the pop-up window layer. Click the close button to close the current pop-up window. The following code is generally used because you need to find an icon, I will not upload images for demo anymore:

$(‘.close-it‘).on(‘click‘,function(event) {    $(this).parents(‘.overlay‘).fadeOut(200,function(){        $(this).removeAttr(‘style‘);    });});

You also need to pay attention to the details. When using jquery for animation, try to use the callback function to clear the style attribute that jquery has added for it, so as to avoid some unexpected problems and the lessons of blood flow.

Note the content of the pop-up window

In fact, it is very simple and reasonable to apply the display: none; for the content block of the pop-up window effect initially, but there will be some unexpected situations in the actual application, pay attention to the pop-up window content.

Some time ago, in projects, the content in the pop-up window was relatively complicated. There were plug-ins such as slides and charts, and the results encountered problems. The slide and chart area contents were misplaced and deformed. Later, I tested and found the cause, because these plug-ins need to calculate the size and position of the outer frame or related elements during initialization. If you set display: none for them, when the plug-in is initialized, the correct data cannot be obtained, and the data is misplaced or invalid.

Therefore, the use of display: none; To hide the pop-up window also needs to be discussed in different situations. In some cases, it is more reasonable to use the Z-index:-1; Method to hide the window. If you need to do an animation, you can set opacity or use the setTimeout Function to add the display: None function to the relevant plug-in after it has obtained the size of the relevant structure after the page is loaded.

Improve the user experience of pop-up windows

The pop-up window above is relatively basic and general. Generally, based on the layout of the pop-up window content block, there are two types:

Page scrolling is allowed after the window pops up

In this method, position: absolute; is usually used. You can check this demo. It is mainly used to deal with the large size of the pop-up window content. If the screen width and height are exceeded, a scroll bar is generated to facilitate the viewer's viewing. Some image pop-up window plug-ins use this method to dynamically calculate the position of the pop-up window content block using JS, so that even if the content block is large, it will not cause information loss.

However, the center usually requires JS cooperation or processing the position and size, which may be a little troublesome.

Page scrolling is not allowed after the window pops up.

You can set position: fixed for the content block so that although it is rolled, the content block is still displayed in the center, giving you a feeling of no scrolling, just commented out the demo and modified it.

You can also set overflow-Y: hidden for HTML and body labels so that the scroll bar disappears and cannot be rolled.

Generally, you need to use hidden to hide the scroll bar and prohibit scrolling. Then you can choose absolute or fixed based on your needs. However, after overflow-Y: hidden is set for HTML or body, the page content is shifted to a whole point because the scroll bar is missing and the width is wider.This affects the user experience !!

Remove the scroll bar but avoid page content offset

Zhihu also mentioned this question some time ago: how to prevent the browser from rolling the scroll bar, but not letting it disappear ?. The answer provided by the TQ senior is simple and convenient, but the actual test is not perfect, because the Chrome browser's scroll bar is 15 PX width, while the Firefox browser is 17 PX. If it is set to 17px in a unified manner, chrome and other browsers will obviously offset 2px. Although we try our best to improve it, it is still a little offset and cannot stand it.

Since different browsers have different scroll bar widths, can I first use js to check the operating system and browser, and then set different offsets based on the browser to be determined? The general idea is correct, but the method is wrong. When detecting operating systems and browsers, there are too many cases to judge and the code is too complicated. So this issue is now available here.

When I accidentally tried Twitter and triggered the pop-up window effect, I accidentally saw that they used this method to hide the scroll bar and ensure that it would not be offset. After testing, the results in various browsers were perfect. So I analyzed their code. below is their function:

function ScrollbarWidth() {    this.calculateScrollbarWidth = function() {        if ($("#scrollbar-width").length > 0) return;        var a = $(‘<div class="modal-measure-scrollbar"/>‘).prependTo($("body")),        b = $(‘<div class="inner"/>‘).appendTo(a),        c = a.width() - b.width();        a.remove(),        $("head").append(‘<style id="scrollbar-width">        .compensate-for-scrollbar,        .modal-enabled,        .modal-enabled .global-nav-inner,        .profile-editing,        .profile-editing .global-nav-inner,        .overlay-enabled,        .overlay-enabled .global-nav-inner,        .grid-enabled,        .grid-enabled .global-nav-inner,        .gallery-enabled,        .gallery-enabled .global-nav-inner {          margin-right: ‘ + c + "px      }      </style>")    }}

The main code is

var a = $(‘<div class="modal-measure-scrollbar"/>‘).prependTo($("body")),b = $(‘<div class="inner"/>‘).appendTo(a),c = a.width() - b.width();a.remove();$("head").append(‘<style id="scrollbar-width"> .compensate-for-scrollbar{ margin-right:‘ + c + ‘px } </style>‘);

The general meaning is to create a new package structure, and then subtract the two widths to get the width of the scroll bar, and then output it to the head. When a pop-up window occurs, assign the corresponding class to the HTML tag to margin-Right to avoid the content offset caused by the disappearance of the scroll bar.

Great! This is the correct solution. Obviously, these two structures need to be assigned CSS for the purpose of making. modal-measure-scrollbar generates a scroll bar while. inner is not including the full width of the scroll bar, and their difference is exactly the width of the scroll bar!

The style of their application in Twitter is as follows:

.modal-measure-scrollbar{    position: absolute;    height: 100px;    width: 100px;    top: -300px;    left: -300px;    overflow: scroll;    z-index: 1000;    overflow-y: scroll;}.modal-measure-scrollbar .inner{    height: 200px;}

No need to explain it.

Later, I tested the fancybox plug-in. Its method is simpler and more general. The specific code is as follows:

w1 = $(window).width();H.addClass(‘fancybox-lock-test‘);w2 = $(window).width();H.removeClass(‘fancybox-lock-test‘);$("<style type=‘text/css‘>.fancybox-margin{margin-right:" + (w2 - w1) + "px;}</style>").appendTo("head");

Here, the H variable is $ ('html '). The purpose is to first detect the existing width, add a class for HTML, then detect the class, and restore the class to get the scroll bar width. The code of the. fancybox-lock-test class is as follows:

.fancybox-lock-test {    overflow-y: hidden !important;}

This method is more clever and simple. You do not need to create a temporary Dom structure. Therefore, we strongly recommend that you use this method in your project.

In addition, there is a third method from QQ space. QQ space albums and so on, also use pop-up window, view their implementation method, is to use a fixed 17px offset value, in other browsers is also 17px pixel. However, it is difficult to see the content offset during use because the background mask layer is too dark and the transparency is not high, so many details are ignored. If your background mask is not very transparent, you obviously do not need to process it ~

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.