search
HomeWeb Front-endJS TutorialHomemade lightweight jQuery.boxy dialog plug-in code_jquery

In this regard, the jquery.boxy plug-in has been made very powerful. Commonly used prompts, confirmations, dragging, changing sizes, and asynchronous loading are all very practical, resulting in larger files (negligible), and many functions are not needed. For this reason , with the attitude and idea of ​​learning and practicing at the same time, I made a lightweight pop-up layer plug-in suitable for this project. This is the first time I write a jqeury plug-in, and I am also preparing to encapsulate common operations into jquery plug-ins in the future. Bar.

First of all, let’s give the plug-in a name so that it can fool people. Let’s call it jquey.cvbox.min.js. cv is the abbreviation of the website domain name ChinaValue. The compressed capacity is controlled below 6K. Since it's not finished yet, I'll write down my thoughts first.

1. Add container elements to the page to display content, as well as the background of the pop-up layer. It only needs to be there. As for where you were born (that is, where it is displayed on the page) and what you will grow into. The appearance will be cultivated (set up) later, and the appearance will naturally be dressed up by the art director.
2. According to our needs, we define some commonly used objects in advance, such as the background of the mask, the container of the pop-up layer, the title bar of the pop-up layer, the content area of ​​the pop-up layer, and the height of the current browser window. Kuan, etc., with these, it will be much more convenient to use later.
3. Start stuffing content into the container. The content can be a prompt (corresponding to the prompt function), a question (corresponding to the confirmation box), a picture (for example, for enlarging a small picture), or It is a piece of HTML code (replacing the inconvenience of writing HTML directly in JS).
4. Define the event that the user clicks to close, that is, hiding or removing the background layer and pop-up layer, leaving it to be called when the operation is completed.
5. Set the background layer transparency and scroll height, set the position of the pop-up layer, center it with scrolling or be fixed.
6. Finally, in order to facilitate use in multiple situations, extract variable parameters. The parameters must have default values, and use $.extend to complete it.

The beta version is expected to be released after the holidays, and it will be unabridged.
Online demo: http://demo.jb51.net/js/jquery_cvbox/index.htm
Package download: http://xiazai.jb51.net/201010/ yuanma/jquery_cvbox.rar
jquery.cvbox.min.js code

Copy code The code is as follows:

/*
* JQuery.cvbox.js
* http://www.chinavalue.net
*
* J.Wang
* http://0417.cnblog.socm
*
* 2010.09.30
*/

(function($) {
$.fn.cvbox = function(options) {
var self = $(this);
var defaults = {
titleBarText: "",
titleBarClose: "关闭",
bgClickClose: false,
bgShow: true,
bgOpacity: 0.2,
confirmText: "",
alertText: "",
delayClose: 0,
submitAfter: function() {
$.noop();
}
};
var param = $.extend({}, defaults, options || {});

//弹框的显示
var cvBoxElement = '
';
cvBoxElement += '
';
cvBoxElement += '
' + param.titleBarText + '
';
cvBoxElement += '
';
cvBoxElement += '
';

if ($("#cvBoxBorder").size()) {
$("#cvBoxBorder").show();

if (param.bgShow) {
$("#cvBoxShade").show();
}
else {
$("#cvBoxShade").hide();
}
}
else {
$("body").append(cvBoxElement);
}

//一些元素对象,浏览器宽高,滚动高度,页面高度
var cbBg = $("#cvBoxShade");
var cbBorder = $("#cvBoxBorder");
var cbTitleBar = $("#cvBoxTitleBar");
var cbBody = $("#cvBoxBody");
var w, h, st, ph;

var cb = {
//装载的内容
content: function() {
var text;

if (param.confirmText != "") {
text = $('
' + param.confirmText + '

  

');
}
else if (param.alertText != "") {
text = $('
' + param.alertText + '

');
}
else {
self.show();
text = self;
}

return text;
},

hw: function(obj) {
//获取任意元素的高宽
var hwSize = {};
$('
').appendTo("body").append(obj.clone());
hwSize.w = $("#cbBox").width();
hwSize.h = $("# cbBox").height();
$("#cbBox").remove();
return hwSize;
},

//The width and height transparency of the black background, etc., The position of the pop-up box
position: function() {
w = $(window).width(), h = $(window).height(), st = $(window).scrollTop(), ph = $(document).height();
cbBg.width(w).height(ph).css("opacity", param.bgOpacity);
//The position of the main content
var x_size = cb.hw(cb.content());
var xh = x_size.h, xw = x_size.w;
var t = st (h - xh) / 2, l = (w - xw) / 2;
cbBorder.css({
width: xw,
top: t,
left: l,
zIndex: 9999
});
},

//Position
posfix: function() {
if (window.XMLHttpRequest) {
cbBorder.css("position", "fixed");
} else {
$(window).scroll(function() {
cb.position();
});
}
},

//center
center : function() {
$(window).resize(function() {
cb.position();
});
},

bgclick: function() {
cbBg.click(function() {
cb.hide();
});
},

bghide: function() {
cbBg.hide ();
},

//Hide the pop-up box
hide: function() {
if (param.confirmText == "" && param.alertText == "") {
cb.content().hide().appendTo($("body"));
}

//cbBorder.fadeOut(300);
cbBorder.remove( );
cbBg.remove();
return false;
},

barhide: function() {
cbTitleBar.hide();
},

show: function() {
if (cbBody.html() == "") {
cbBody.append(cb.content());
}

cb.position();
cb.center();

if (param.titleBarText == "") {
cb.barhide();
}
if ( !param.bgShow) {
cb.bghide();
}
if (param.bgClickClose) {
cb.bgclick();
}
if (param.delayClose > 0) {
setTimeout(cb.hide, param.delayClose);
}
}
};

cb.show();

//Binding of some events
$("#cvBoxBtnSubmit").bind("click", function() {
if (param.confirmText != ""){
param.submitAfter() ;
}
cb.hide();
});

$("#cvBoxBtnCancel").bind("click", function() {
cb.hide ();
});

$("#cvBoxTitleBarClose").bind("click", function() {
cb.hide();
});
}
})(jQuery);

Complete test code
Copy code The code is as follows:








未压缩版本是6K大小,压缩后只有2K大,应该算很轻了。

 



1.弹出提示框,点击查看效果。



$(this).cvbox({ <BR>titleBarText: "弹出提示框", <BR>alertText: "世界上最远的距离不是生与死的距离<br />而是我在你面前<br />你却不知道我爸爸是李刚" <BR>}); <BR>



2. 효과를 보려면 클릭하세요.



$("# A2").click(function() { <BR>$(this).cvbox({ <BR>titleBarText: "팝업 프롬프트 상자는 1초 후에 자동으로 닫힙니다.", <BR>alertText: "가장 먼 거리 세상에는 삶과 죽음의 거리가 없습니다<br /&gt ;하지만 나는 당신 앞에 있습니다<br />당신은 내 아버지가 리강이라는 것을 모르고 있습니다", <BR>delayClose:1000 <BR> }); <BR>

3. 대화 상자가 나타나면 클릭하여 효과를 확인하세요.



$("#A3"). click(function() { <BR>$(this).cvbox({ <BR>titleBarText: "팝업 대화 상자", <BR>confirmText: "세상에서 가장 먼 거리는 삶과 죽음의 거리가 아닙니다&lt ;br /> 근데 나야 너 앞에서는<br />그런데 내 아버지가 리강이라는 걸 모르시나봐요<br <BR>/><br />네 아버지가 리강인 게 확실해? Gang? ", <BR>submitAfter:HelloLiGang <BR>}); <BR>}); <BR><BR>function HelloLiGang(){ <BR>alert("아버지에 대한 존경심은 끝없는 강과 같습니다! "); <br>} <br>&lt ;/pre> <BR></div> <BR><div> <BR><a id="A4" href="javascript:void(0) ;">4. HTML 콘텐츠를 로드하고 클릭하여 효과를 확인하세요. </a> <BR><div class="A4Demo" style="display: none; width: 550px; padding: 10px;"> <BR><div> <BR>이 콘텐츠의 일반적인 표시 이는 HTML 콘텐츠가 동적으로 작성되지 않고 현재 페이지에 있음을 보여주기 위한 것입니다. <BR>. <BR><br /> <BR>콘텐츠는 iframe을 포함한 모든 요소일 수 있습니다. <BR></div> <BR><div> <BR></div> <BR><script type="text/javascript"< ![CDATA[ <BR>$("#A4").click(function() { <BR>$(".A4Demo").cvbox({ <BR>titleBarText: "HTML 콘텐츠 로드" <BR> }); <BR>// ]]</script> <BR></div><BR><BR>< pre class="brush:html"><div class="A4Demo" style="display:none; width:550px; padding:10px; "> <BR><div> 표시가 숨겨짐으로 설정되어 있습니다. 이는 HTML 콘텐츠가 동적으로 작성되지 않고 현재 페이지에 있음을 보여주기 위한 것입니다. <BR><br /> <BR>콘텐츠는 iframe을 포함한 모든 요소일 수 있습니다. <BR></div> <BR><div> <BR><iframe width="100%"frameborder="0" src="http://a.cvimg.cn/UploadFile/MiniBlog/2010 /10-20/7a09cf13-eeb6-491b-aa63- <BR>18dd67bde0a1_Big.jpg"></iframe> <BR></div> <BR></div> <BR></pre&gt ; <BR></div> <BR><br /> <BR><div class="jb51_Highlighter"><BR><pre class="brush:javascript">$("# A4").click(function() { <BR>$(".A4Demo").cvbox({ <BR>titleBarText: "HTML 콘텐츠 로드 중" <BR>}); <BR>}); <BR>



그래야 대화상자 레이어가 화면 중앙에만 표시됩니다.



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
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

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment