Home  >  Article  >  Web Front-end  >  Javascript public script library series (1): Pop-up layer script_javascript skills

Javascript public script library series (1): Pop-up layer script_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:10:20863browse
1. Summary
This series of articles is to abstract common, cross-browser scripting methods.

This article explains the javascript function that pops up the floating layer, as well as the principle and function of the function. Precautions for use.

2. Achieving the effect
Using a script to pop up the floating layer is one of our most commonly used scripting methods. The following is the rendering:

image
After clicking "Airline" in the picture, a floating layer will pop up under "Airline".

There are quite a lot of scripts for pop-up boxes on the Internet , and there are various third-party JS frameworks available for us to use. However, some of the scripts are too simple, only roughly achieving the pop-up effect and ignoring flexibility, versatility and cross-browser features. Using JS frameworks is a bit of a waste. It’s a good idea. So after collecting and sorting out some information, I wrote the pop-up layer method of the ScriptHelper class below.

The main features are:
Supports multiple browsers
Using object-oriented method encapsulation
Easy to use and highly versatile.
Extract functions such as calculating position. All related functions can be called separately, and secondary development can be continued according to specific projects.
3. Script method
Below I will first contribute the script method, and then give examples of how to use it. Finally, I will explain the principle of the script.

Copy codeThe code is as follows:

/* ==================== ScriptHelper 开始 ==================== */
/* scriptHelper 脚本帮助对象.
创建人: ziqiu.zhang 2008.3.5
添加函数:
getScroll():得到鼠标滚过的距离-兼容XHTML
getClient():得到浏览器当前显示区域的大小-兼容XHTML
showDivCommon():显示图层.
使用举例:


*/
function scriptHelper()
{
}

// 得到鼠标滚过的距离 scrollTop 与 scrollLeft
/* 用法与测试:
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.documentElement.scrollTop)? document.body.scrollTop:document.documentElement.scrollTop;
if( isNaN(scrollTop) || scrollTop <0 ){ scrollTop = 0 ;}
scrollLeft = (document.body.scrollLeft > document.documentElement.scrollLeft )? document.body.scrollLeft:document.documentElement.scrollLeft;
if( isNaN(scrollLeft) || scrollLeft <0 ){ scrollLeft = 0 ;}
return { scrollTop:scrollTop, scrollLeft: scrollLeft};
}
// 得到浏览器当前显示区域的大小 clientHeight 与 clientWidth
/* 用法与测试:
var myScroll = getScroll();
alert("myScroll.sTop:" + myScroll.sTop);
alert("myScroll.sLeft:" + myScroll.sLeft);
*/
scriptHelper.prototype.getClient = function ()
{
//判断页面是否符合XHTML标准
var isXhtml = true;
if( document.documentElement == null || document.documentElement.clientHeight <= 0)
{
if( document.body.clientHeight>0 )
{
isXhtml = false;
}
}
this.clientHeight = isXhtml?document.documentElement.clientHeight:document.body.clientHeight;
this.clientWidth = isXhtml?document.documentElement.clientWidth:document.body.clientWidth;
return {clientHeight:this.clientHeight,clientWidth:this.clientWidth};
}

// 显示图层,再次调用则隐藏
/* 参数说明:
sObj : 要弹出图层的事件源
divId : 要显示的图层ID
sObjHeight : 事件源的高度,默认为20.需要手工传入是因为对于由于事件源对象可能是各种HTML元素,有些元素高度的计算无法跨浏览器通用.
moveLeft : 手工向左移动的距离.不移动则为0(默认).
divObjHeight: 弹出层的高度.如果传入大于0的此参数, 则当事件源下方空间不足时,在事件源上方弹出层.如果不传此参数则一直在事件源下方弹出.
用法与测试:

*/
scriptHelper.prototype.showDivCommon = function (sObj,divId, sObjHeight, moveLeft, divObjHeight)
{
//Cancel the bubbling 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 parameters are passed in, set the default value
if( moveLeft == null )
{
moveLeft = 0;
}
if( sObjHeight == null )
{
sObjHeight = 20;
}
if(divObjHeight == null)
{
divObjHeight = 0;
}

var divObj = document.getElementById(divId); //Get the layer object
var sObjOffsetTop = 0; //Vertical distance of event source
var sObjOffsetLeft = 0; //Horizontal distance of event source
var myClient = this.getClient();
var myScroll = this.getScroll();
var sWidth = sObj.width; //Width of the event source object
var sHeight = sObjHeight; //Height of the event source object
var bottomSpace; //Distance from the bottom
/* Get The height and width of the event source control.*/
if( sWidth == null )
{
sWidth = 100;//If it cannot be obtained, it is 100
}
else
{
sWidth = sWidth 1; //leave 1px distance
}

if( divObj.style.display.toLowerCase() != "none" )
{
/ /Hide layer
divObj.style.display = "none";
}
else
{
if( sObj == null )
{
alert("event The source object is null");
return false;
}
/* Get the offset of the event source object*/
var tempObj = sObj; //Temporary used to calculate the event source coordinates Object
while( tempObj && tempObj.tagName.toUpperCase() != "BODY" )
{
sObjOffsetTop = tempObj.offsetTop;
sObjOffsetLeft = tempObj.offsetLeft;
tempObj = tempObj. offsetParent;
}
tempObj = null;

/* Get the distance from the bottom*/
bottomSpace = parseInt(myClient.clientHeight) - ( parseInt(sObjOffsetTop) - parseInt(myScroll. scrollTop)) - parseInt(sHeight);
/* Set the layer display position*/
//If there is insufficient space below the event source and the upper control is enough to accommodate the pop-up layer, it will be displayed above. Otherwise, it will be displayed below
if( divObjHeight>0 && bottomSpace < divObjHeight && sObjOffsetTop >divObjHeight )
{
divObj.style.top = ( parseInt( sObjOffsetTop ) - parseInt( divObjHeight ) - 10).toString() "p x ";
}
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 testing:
ScriptHelper.closeDivCommon('testDiv');
*/
scriptHelper.prototype.closeDivCommon = function (divId)
{
//
var divObj = document.getElementById(divId); //Get the layer object
if( divObj != null )
{
divObj.style.display = "none";
}
}
//Create an instance object of the scriptHelper class. Use it globally.
var ScriptHelper = new scriptHelper() ;
/* ==================== ScriptHelper end ==================== */

4. Usage Example
Next we create an HTML page to demonstrate how to use this script. This example is a menu that displays a submenu layer when clicked.
1. Reference the script file
Save the above code in the ScriptHelper.js file. Add a reference to the page:

2. Write submenus
First write two submenu layers.
Copy code The code is as follows:






For submenus, the most important thing is to set two styles: position and display.
position:absolute allows this layer to be accurately positioned and displayed, thereby controlling its display position.
display:none allows the layer not to be displayed when loading.
3. Write the main menu
main menu code As follows:
Copy code The code is as follows:

We created three menus. Among them Menu1 and Menu2 Has a submenu, NoSubMenu does not have a submenu.
We used the a element to create the menu object, but because no href attribute was added to it, by default it will not turn into a hand graphic when the mouse is placed on it. You need to add the style cursorHand to it , the code of the sub-style is as follows:

The most important thing is for the menu Added onclick event, this event calls the ScriptHelper.showDivCommon method to display the layer.
The first parameter value of the method is this, which means that the event source object is passed in, and the display position is calculated based on the event source in the function.
The second parameter of the method represents the Id of the pop-up image
The third parameter of the method is an optional parameter, used to set the downward offset. Because the position we calculate is "Menu1 "The coordinates of the upper left corner of this element. A downward offset needs to be set. Generally set to the height of the event source, the default is 20px. The fourth parameter of the
method is an optional parameter, used to set the left offset. Shift amount. The reason is the same as above. The default is 0px; the fifth parameter of the
method is an optional parameter and needs to be passed in the height of the pop-up layer. If this attribute is used, the pop-up layer may pop up above the event source. Do not pass this attribute The layer will always pop up below the event source.
4. Effect and complete code

image
The complete example code is as follows:

Copy code The code is as follows:




ScriptHelper class test page</ title> <br><script src="http://files.cnblogs.com/zhangziqiu/ScriptHelper.js" type="text/javascript" defer="defer"></script> <br>< ;style type="text/css"> <br>.cursorHand { cursor:pointer;} <br></style> <br></head> <br><body style="position:relative ;"> <br><div style="height:200px;"></div> <br><!-- Main Menu --> <br><div > <br> <a class="cursorHand" onclick="ScriptHelper.showDivCommon(this,'subMenu1', 20, 0, 100)">Menu1</a> <br><a class="cursorHand" onclick="ScriptHelper .showDivCommon(this,'subMenu2', 20, 0)">Menu2</a> <br><a class="cursorHand" href="#">NoSubMenu</a> <br></ div> <br><!-- Sub Menu 1 --> <br><div id="subMenu1" style="position:absolute; display:none; background-color:#D7EFCD; border:solid 1px #000000; margin:0px; padding:5px; height:100px;"> <br><div>1-1</div> <br><div>1-2</div> <br>< ;/div> <br><!-- Sub Menu 2 --> <br><div id="subMenu2" style="position:absolute; display:none; background-color:#D7EFCD; border: solid 1px #000000; padding:5px;" > <br><div>2-1</div> <br><div>2-2</div> <br></div> <br></body> <br></html> <br> </div> <br><strong>5. 참고</strong>: <br>1. Body 요소에 position:relative 스타일을 추가합니다. <br><body style="position:relative;"> , 때로는 IE6에서 이벤트 소스를 정확하게 찾을 수 없습니다. 예를 들어, 메뉴의 <div>에 여러 개의 <br/>가 추가되면 팝업 레이어의 위치가 잘못됩니다. Body 요소에 이 스타일을 추가했는데도 여전히 팝업 위치가 잘못된 경우 이벤트 소스 객체의 컨테이너 요소에 이 스타일을 추가하세요.<br>2. 마지막 매개변수가 전달되지 않으면 팝업이 발생합니다. 위쪽 레이어는 이벤트 소스 아래에만 팝업됩니다. 그렇지 않으면 이벤트가 계산됩니다. 예를 들어 소스 하단에서 아래쪽 컨트롤이 부족하고 위쪽 컨트롤이 충분하면 팝업 레이어가 위에 표시됩니다. <br>3. DOCTYPE 요소를 페이지에 추가합니다. 추가하지 않으면 일부 브라우저에서 오류가 발생할 수 있습니다. <br><br>DOCTYPE 문서를 참조하세요. 요소 분석<br><a href="http://www.jb51.net/web/34579.html" target="_blank">6. 요약</a><br>이 기능에는 여전히 문제가 있을 것 같아 여러 브라우저와의 호환성이 정말 골치 아픈 문제입니다. , 하지만 작성하는 동안 몇 가지 버그를 발견하고 수정했습니다. 호환성이 왔다 갔다 하다가 결국 호환성을 잃었습니다. 사실, 프로젝트가 가능하다면 이 시리즈의 기사는 빌드하는 것이 좋은 선택이 될 것입니다. 가벼운 스크립트 라이브러리입니다. 사용 중에 궁금한 점이 있으면 더 많이 소통하고 간단하고 사용하기 쉬운 스크립트 라이브러리를 함께 만들어 보세요!</div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>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</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="JavaScript ( (__ = !$ $)[ $] ({} $)[_/_] ({} $)[_/_] )_javascript skills" href="http://m.php.cn/faq/20414.html">JavaScript ( (__ = !$ $)[ $] ({} $)[_/_] ({} $)[_/_] )_javascript skills</a></span><span>Next article:<a class="dBlack" title="JavaScript ( (__ = !$ $)[ $] ({} $)[_/_] ({} $)[_/_] )_javascript skills" href="http://m.php.cn/faq/20416.html">JavaScript ( (__ = !$ $)[ $] ({} $)[_/_] ({} $)[_/_] )_javascript skills</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1609.html" title="An in-depth analysis of the Bootstrap list group component" class="aBlack">An in-depth analysis of the Bootstrap list group component</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1640.html" title="Detailed explanation of JavaScript function currying" class="aBlack">Detailed explanation of JavaScript function currying</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1949.html" title="Complete example of JS password generation and strength detection (with demo source code download)" class="aBlack">Complete example of JS password generation and strength detection (with demo source code download)</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2248.html" title="Angularjs integrates WeChat UI (weui)" class="aBlack">Angularjs integrates WeChat UI (weui)</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2351.html" title="How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills" class="aBlack">How to quickly switch between Traditional Chinese and Simplified Chinese with JavaScript and the trick for websites to support switching between Simplified and Traditional Chinese_javascript skills</a><div class="clear"></div></li></ul></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="http://m.php.cn/"><b class="icon1"></b><p>Home</p></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="http://m.php.cn/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="http://m.php.cn/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="http://m.php.cn/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="http://m.php.cn/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="http://m.php.cn/" >Home</a></div><div class="swiper-slide"><a href="http://m.php.cn/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="http://m.php.cn/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="http://m.php.cn/course.html" >Course</a></div><div class="swiper-slide"><a href="http://m.php.cn/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="http://m.php.cn/xiazai" >Download</a></div><div class="swiper-slide"><a href="http://m.php.cn/game" >Game</a></div><div class="swiper-slide"><a href="http://m.php.cn/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs" ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan " href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a onclick="javascript:;" class="language course-right-orders chooselan chooselanguage" href="javascript:;"><span>English</span><span>(EN)</span></a><a onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan " href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a><a onclick="javascript:setlang('ja');" class="language course-right-orders chooselan " href="javascript:;"><span>日本語</span><span>(JA)</span></a><a onclick="javascript:setlang('ko');" class="language course-right-orders chooselan " href="javascript:;"><span>한국어</span><span>(KO)</span></a><a onclick="javascript:setlang('ms');" class="language course-right-orders chooselan " href="javascript:;"><span>Melayu</span><span>(MS)</span></a><a onclick="javascript:setlang('fr');" class="language course-right-orders chooselan " href="javascript:;"><span>Français</span><span>(FR)</span></a><a onclick="javascript:setlang('de');" class="language course-right-orders chooselan " href="javascript:;"><span>Deutsch</span><span>(DE)</span></a></div></div><script> var swiper = new Swiper('.nphpNavSwiper1', { slidesPerView : 'auto', observer: true,//修改swiper自己或子元素时,自动初始化swiper observeParents: true,//修改swiper的父元素时,自动初始化swiper }); </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>