Javascript common script Library series (1): pop-up layer script

Source: Internet
Author: User

I. Summary
This series of articles aims to abstract common, cross-Browser Scripting methods.

This article explains the javascript Functions on the floating layer and the principles and precautions of the functions.

II. Implementation results
Using the script to pop up the floating layer is one of our most common script methods. The following is:

 
Click "Airline" in the figure and a floating layer will pop up under "Airline.

There are a lot of scripts in the pop-up box on the Internet, and there are various third-party JS frameworks available for us. however, some of the scripts are too simple. They just roughly implement the pop-up effect and ignore the flexibility, versatility, and cross-browser features. using the JS framework, some of them use a cool tool. after collecting and sorting out some information, I wrote the pop-up method of the ScriptHelper class below.

Main features include:
Support for multiple browsers
Use object-oriented method Encapsulation
Easy to use and versatile.
Extract the computing location and other functions. All related functions can be called independently. You can continue secondary development based on the specific project.
Iii. Script Method
Next, I will first contribute the script method, and then give an example of how to use it. Finally, I will explain the script principle.

Copy codeThe Code is as follows:
/* ============================== ScriptHelper start ====================== ==== */
/* ScriptHelper script help object.
Created by: ziqiu. zhang 2008.3.5
Add function:
GetScroll (): Get the distance from mouse rolling-compatible with XHTML
GetClient (): Get the size of the current display area of the browser-compatible with XHTML
ShowDivCommon (): Display layer.
Example:
<Div id = "testDiv" style = "display: none; position: absolute; border: 1px #000000;"> I'm a test layer, I'm a test layer </div>
<Div style = "width: 400px; text-align: center;"> <div> <a href = "#" onclick = "ScriptHelper. showDivCommon (this, 'testdiv ', 20, 70) "> event source </a> </div>
*/
Function scriptHelper ()
{
}

// Obtain the distance between scrollTop and scrollLeft
/* Usage and test:
Var myScroll = getScroll ();
Alert ("myScroll. scrollTop:" + myScroll. scrollTop );
Alert ("myScroll. scrollLeft:" + myScroll. scrollLeft );
*/
ScriptHelper. prototype. getScroll = function ()
{
Var scrollTop = 0, scrollLeft = 0;
ScrollTop = (document. body. scrollTop> document.doc umentElement. scrollTop )? Document. body. scrollTop: document.doc umentElement. scrollTop;
If (isNaN (scrollTop) | scrollTop <0) {scrollTop = 0 ;}
ScrollLeft = (document. body. scrollLeft> document.doc umentElement. scrollLeft )? Document. body. scrollLeft: document.doc umentElement. scrollLeft;
If (isNaN (scrollLeft) | scrollLeft <0) {scrollLeft = 0 ;}
Return {scrollTop: scrollTop, scrollLeft: scrollLeft };
}
// Obtain the clientHeight and clientWidth of the current display area of the browser.
/* Usage and test:
Var myScroll = getScroll ();
Alert ("myScroll. sTop:" + myScroll. sTop );
Alert ("myScroll. sLeft:" + myScroll. sLeft );
*/
ScriptHelper. prototype. getClient = function ()
{
// Determine whether the page meets the XHTML Standard
Var isXhtml = true;
If (document.doc umentElement = null | document.doc umentElement. clientHeight <= 0)
{
If (document. body. clientHeight> 0)
{
IsXhtml = false;
}
}
This. clientHeight = isXhtml? Document.doc umentElement. clientHeight: document. body. clientHeight;
This. clientWidth = isXhtml? Document.doc umentElement. clientWidth: document. body. clientWidth;
Return {clientHeight: this. clientHeight, clientWidth: this. clientWidth };
}

// Display the layer, which is hidden when called again
/* Parameter description:
SObj: Event source for the layer to be popped up
DivId: ID of the layer to be displayed
SObjHeight: the height of the event source. The default value is 20. You need to manually input it because the event source object may be a variety of HTML elements, and the calculation of the height of some elements cannot be used across browsers.
MoveLeft: the distance to move manually to the left. If it is not moved, it is 0 (default ).
DivObjHeight: the height of the pop-up layer. if this parameter is input greater than 0, a layer is displayed on the event source when the space below the event source is insufficient. if this parameter is not set, it is always displayed below the event source.
Usage and test:
<Div> <a href = "#" onclick = "ScriptHelper. showDivCommon (this, 'testdiv ', 20, 20)"> event source </a> </div>
*/
ScriptHelper. prototype. showDivCommon = function (sObj, divId, sObjHeight, moveLeft, divObjHeight)
{
// Cancel the bubble event
If (typeof (window )! = 'Undefined' & window! = Null & window. event! = Null)
{
Window. event. cancelBubble = true;
}
Else if (ScriptHelper. showDivCommon. caller. arguments [0]! = Null)
{
ScriptHelper. showDivCommon. caller. arguments [0]. cancelBubble = true;
}
// Parameter detection. If no parameter is input, the default value is set.
If (moveLeft = null)
{
MoveLeft = 0;
}
If (sObjHeight = null)
{
SObjHeight = 20;
}
If (divObjHeight = null)
{
DivObjHeight = 0;
}

Var divObj = document. getElementById (divId); // obtain the layer object
Var sObjOffsetTop = 0; // vertical distance of the event Source
Var sObjOffsetLeft = 0; // horizontal distance of the event Source
Var myClient = this. getClient ();
Var myScroll = this. getScroll ();
Var sWidth = sObj. width; // The width of the event source object
Var sHeight = sObjHeight; // The height of the event source object
Var bottomSpace; // distance from the bottom
/* Obtain the height and width of the event source control .*/
If (sWidth = null)
{
SWidth = 100; // The value is 100 if it cannot be obtained.
}
Else
{
SWidth = sWidth + 1; // leave the 1px distance
}

If (divObj. style. display. toLowerCase ()! = "None ")
{
// Hide the Layer
DivObj. style. display = "none ";
}
Else
{
If (sObj = null)
{
Alert ("event source object is null ");
Return false;
}
/* Get the offset of the event source object */
Var tempObj = sObj; // a temporary object used to calculate the coordinates of the event Source
While (tempObj & tempObj. tagName. toUpperCase ()! = "BODY ")
{
SObjOffsetTop + = tempObj. offsetTop;
SObjOffsetLeft + = tempObj. offsetLeft;
TempObj = tempObj. offsetParent;
}
TempObj = null;

/* Obtain the distance from the bottom */
BottomSpace = parseInt (myClient. clientHeight)-(parseInt (sObjOffsetTop)-parseInt (myScroll. scrollTop)-parseInt (sHeight );
/* Set the layer display position */
// If there is not enough space at the bottom of the event source and the upper control is sufficient to accommodate the pop-up layer, it will be shown above. Otherwise, it will be shown below.
If (divObjHeight> 0 & bottomSpace <divObjHeight & sObjOffsetTop> divObjHeight)
{
DivObj. style. top = (parseInt (sObjOffsetTop)-parseInt (divObjHeight)-10). toString () + "px ";
}
Else
{
DivObj. style. top = (parseInt (sObjOffsetTop) + parseInt (sHeight). toString () + "px ";
}
DivObj. style. left = (parseInt (sObjOffsetLeft)-parseInt (moveLeft). toString () + "px ";
DivObj. style. display = "block ";
}
}

// Close the Layer
/* Parameter description:
DivId: ID of the layer to be hidden
Usage and test:
ScriptHelper. closeDivCommon ('testdiv ');
*/
ScriptHelper. prototype. closeDivCommon = function (divId)
{
//
Var divObj = document. getElementById (divId); // obtain the layer object
If (divObj! = Null)
{
DivObj. style. display = "none ";
}
}
// Create an Instance Object of the scriptHelper class. It is used globally.
Var ScriptHelper = new scriptHelper ();
/* ============================== ScriptHelper end ====================== ==== */

Iv. Examples
Next, we will create an HTML page to demonstrate how to use this script. This instance is a menu and a sub-menu layer will be displayed when you click it.
1. reference the script file
Save the above Code in the ScriptHelper. js file. add reference to the page:
<Script src = "http://files.cnblogs.com/zhangziqiu/ScriptHelper.js" type = "text/javascript" defer = "defer"> </script>
2. Write a sub-menu
Write two sub-menu layers first.
Copy codeThe Code is as follows:
<! -- Sub Menu 1 -->
<Div id = "subMenu1" style = "position: absolute; display: none; background-color: # D7EFCD; border: solid 1px #000000; margin: 0px; padding: 5px; height: 100px; ">
<Div> 1-1 </div>
<Div> 1-2 </div>
</Div>
<! -- Sub Menu 2 -->
<Div id = "subMenu2" style = "position: absolute; display: none; background-color: # D7EFCD; border: solid 1px #000000; padding: 5px;">
<Div> 2-1 </div>
<Div> 2-2 </div>
</Div>

For sub-menus, the most important thing is to set two styles: position and display.
Position: absolute allows this layer to precisely locate the display and control its display position.
Display: none.
3. Compile the main menu
The main menu code is as follows:
Copy codeThe Code is as follows:
<! -- Main Menu -->
<Div>
<A class = "cursorHand" onclick = "ScriptHelper. showDivCommon (this, 'submenu1 ', 20, 0,100)"> Menu1 </a>
<A class = "cursorHand" onclick = "ScriptHelper. showDivCommon (this, 'submenu2 ', 20, 0)"> Menu2 </a>
<A class = "cursorHand" href = "#"> NoSubMenu </a>
</Div>

Three menus are created. Menu1 and Menu2 have sub-menus, and NoSubMenu has no sub-menus.
We used element a to create a menu object, but because we didn't add the href attribute to it, by default, the cursor is not changed to a hand image. you need to add a style cursorHand for it. The code for the secondary style is as follows:
<Style type = "text/css">
. CursorHand {cursor: pointer ;}
</Style>
The most important thing is the onclick event added to the menu. This event calls the ScriptHelper. showDivCommon method to display layers.
The first parameter value of this method indicates that the event source object is passed in. In the function, the display position is calculated based on the event source.
Method. The second parameter indicates the Id of the pop-up image.
The third parameter of the method is an optional parameter, which is used to set the downward offset. because we calculated the coordinates in the upper left corner of the element "<a> Menu1 </a>. you need to set a downward offset. generally, it is set to the height of the event source. The default value is 20px.
The fourth parameter of the method is an optional parameter, which is used to set the offset to the left. The reason is the same as above. The default value is 0px;
The fifth parameter of the method is an optional parameter, and the height of the pop-up layer needs to be input. if this attribute is used, the pop-up layer may pop up on the event source. if this attribute is not passed, a layer is always displayed below the event source.
4. Effects and complete code

 
The complete instance code is as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> ScriptHelper test page </title>
<Script src = "http://files.cnblogs.com/zhangziqiu/ScriptHelper.js" type = "text/javascript" defer = "defer"> </script>
<Style type = "text/css">
. CursorHand {cursor: pointer ;}
</Style>
</Head>
<Body style = "position: relative;">
<Div style = "height: 200px;"> </div>
<! -- Main Menu -->
<Div>
<A class = "cursorHand" onclick = "ScriptHelper. showDivCommon (this, 'submenu1 ', 20, 0,100)"> Menu1 </a>
<A class = "cursorHand" onclick = "ScriptHelper. showDivCommon (this, 'submenu2 ', 20, 0)"> Menu2 </a>
<A class = "cursorHand" href = "#"> NoSubMenu </a>
</Div>
<! -- Sub Menu 1 -->
<Div id = "subMenu1" style = "position: absolute; display: none; background-color: # D7EFCD; border: solid 1px #000000; margin: 0px; padding: 5px; height: 100px; ">
<Div> 1-1 </div>
<Div> 1-2 </div>
</Div>
<! -- Sub Menu 2 -->
<Div id = "subMenu2" style = "position: absolute; display: none; background-color: # D7EFCD; border: solid 1px #000000; padding: 5px;">
<Div> 2-1 </div>
<Div> 2-2 </div>
</Div>
</Body>
</Html>

5. Precautions:
1. Add the position: relative style to the Body element:
<Body style = "position: relative;">
If no value is added, the event source cannot be precisely located in IE6. for example, if you add a few <br/> to <div> of menu, the position of the pop-up layer is incorrect.
If you add this style to the Body element and the position is still displayed, add this style to the container element of the event source object.
2. if the last parameter is not passed, the pop-up layer only pops up under the event source. otherwise, the example at the bottom of the event source is calculated. If the bottom control is insufficient and the upper control is sufficient, the pop-up layer is displayed on the event source.
3. Add the DOCTYPE element on the page. If you do not add the DOCTYPE element, errors may occur in some browsers. For more information about DOCTYPE, see the following article:
DOCTYPE element Parsing
Vi. Summary
Compatibility with multiple browsers is really a headache. I guess this function is still faulty. I wanted to write a script for analysis, but I found some bugs during my writing and corrected them. compatibility. in fact, it would be a good choice if a project can use the script library. this series of articles only hope to build a lightweight script class library. if you have any questions, please contact us and create a simple and easy-to-use script library!

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.