Home Web Front-end JS Tutorial Introduction to the use of a share button plug-in (extensible, development and production process included)_jquery

Introduction to the use of a share button plug-in (extensible, development and production process included)_jquery

May 16, 2016 pm 06:02 PM
share button

A few days ago, I needed to make a share button due to work. Considering that it may be used in other subsequent projects, I planned to write it as a plug-in. I just happened to add one to my own plug-in jquery.hooray In order not to waste everyone’s time on the new function, I will release the demo first. If you think it can be used, or want to learn how to make it, then continue reading. (demo)

Since it is going to be a plug-in, it must be highly customizable and cannot be fixed. For example, the number of displays cannot be fixed, the order of sharing buttons cannot be fixed, etc. (But some things still have to be fixed, it is too flexible. It will not become a plug-in). My method of operation here is... look at the code first

Copy the code The code is as follows:

I share all The buttons are all made with the A tag, and then a div container is used to wrap them inside. As long as the A tag is used in this container, and the class name is named according to my regulations, everything is OK. As for the display The quantity, order, etc. are arbitrary.
After the HTML specifications are formulated, you can start writing CSS styles. It should be noted that in order to reduce HTTP requests, I used CSS sprites to splice the button images together, such as

At the same time, I also made a 32*32 large icon version. Of course, you can also make other sizes according to your personal needs. The following is the css code. There is not much to introduce, just take a look.

Copy code The code is as follows:

.hr-share-16 a{display:block; width:18px;height:16px;background:url(HRico_16x16.png) no-repeat;float:left;cursor:pointer}
.hr-share-16 a:hover{opacity:0.8}
.hr -share-16 a.hr-share-more{background-position:0 0}
.hr-share-16 a.hr-share-tsina{background-position:0 -16px}
.hr- share-16 a.hr-share-tqq{background-position:0 -32px}
.hr-share-16 a.hr-share-qzone{background-position:0 -48px}
.hr- share-16 a.hr-share-renren{background-position:0 -64px}
.hr-share-16 a.hr-share-baidu{background-position:0 -80px}
.hr- share-16 a.hr-share-115{background-position:0 -96px}
.hr-share-16 a.hr-share-tsohu{background-position:0 -112px}
.hr- share-16 a.hr-share-taobao{background-position:0 -128px}
.hr-share-16 a.hr-share-xiaoyou{background-position:0 -144px}
.hr- share-16 a.hr-share-hi{background-position:0 -160px}
.hr-share-16 a.hr-share-fanfou{background-position:0 -176px}
.hr- share-16 a.hr-share-sohubai{background-position:0 -192px}
.hr-share-16 a.hr-share-feixin{background-position:0 -208px}
.hr- share-16 a.hr-share-youshi{background-position:0 -224px}
.hr-share-16 a.hr-share-tianya{background-position:0 -240px}
.hr- share-16 a.hr-share-msn{background-position:0 -256px}
.hr-share-16 a.hr-share-douban{background-position:0 -272px}
.hr- share-16 a.hr-share-twangyi{background-position:0 -288px}
.hr-share-16 a.hr-share-mop{background-position:0 -304px}

Here I specially added the prefix .hr-share-16 to the style of each button. The first purpose is to distinguish the 16*16 and 32*32 icon styles, and the second is to facilitate the subsequent operation of the js code part. , I will talk about it later.
After completing the above two steps, the next focus is on writing JS. Before that, let’s sort out the ideas first to prevent rewriting after we finish writing JS and find a better way.
First of all, each website has its own specific sharing link code. Let’s randomly pick 2 for reference, such as Tencent Weibo and Sina Weibo, which are very popular recently.
view sourceprint?http://v.t.qq.com/share/share.php?title=Share plug-in-jquery.HooRay-jQuery plug-in-Produced by: Hu Yirui丶&url=http://saw.caifutang.com/jquery .hooray/HRshare.html&appkey=118cd1d635c44eab9a4840b2fbf8b0fb
view sourceprint?http://service.weibo.com/share/share.php?title=Share plug-in - jquery.HooRay - jQuery plug-in - Produced by: Hu Yirui丶&url=http: //saw.caifutang.com/jquery.hooray/HRshare.html&source=bookmark&appkey=2992571369
Did you find it? Yes, a general sharing link only requires two parameters, one is the title of the page, and the other is the link to the page. As for Tencent Weibo and Sina Weibo, both require an appkey. This is another matter. If not, just use me The one provided will do, because appkey needs to be applied for, and the process is a little cumbersome.
Next, if you master this, the operation will be simple. We only need to bind a click event to each button, and then transfer to the specified link, and everything will be OK. But if you manually bind one by one, it feels very troublesome, and if you add a new share, the amount of code changes seems to be a bit large, and there are many lines of code. Therefore, I bind button events through a loop. Let’s take a look at some code snippets.
First, I defined these two arrays (the indentation of the tab key does not work here, let’s make do with it):
Copy code The code is as follows:

var shareico = {
"tqq" :"http://v.t.qq.com/share/share.php?title={title }&url={url}&appkey=118cd1d635c44eab9a4840b2fbf8b0fb",
"tsina" :"http://service.weibo.com/share/share.php?title={title}&url={url}&source=bookmark&appkey=2992571369 ",
"qzone" :"http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url={url}&title={title}",
"renren" :" http://share.renren.com/share/buttonshare.do?link={url}&title={title}",
"baidu" :"http://cang.baidu.com/do/add? it={title}&iu={url}&fr=ien#nw=1",
"115" :"http://sc.115.com/add?url={url}&title={title}" ,
"tsohu" :"http://t.sohu.com/third/post.jsp?url={url}&title={title}&content=utf-8",
"taobao" :" http://share.jianghu.taobao.com/share/addShare.htm?url={url}",
"xiaoyou" :"http://sns.qzone.qq.com/cgi-bin/qzshare /cgi_qzshare_onekey?to=pengyou&url={url}",
"hi" :"http://apps.hi.baidu.com/share/?url={url}&title={title}",
"fanfou" :"http://fanfou.com/sharer?u={url}&t={title}",
"sohubai" :"http://bai.sohu.com/share/blank/add .do?link={url}",
"feixin" :"http://space3.feixin.10086.cn/api/share?title={title}&url={url}",
" youshi" :"http://www.ushi.cn/feedShare/feedShare!sharetomicroblog.jhtml?type=button&loginflag=share&title={title}&url={url}",
"tianya" :"http:// share.tianya.cn/openapp/restpage/activity/appendDiv.jsp?app_id=jiathis&ccTitle={title}&ccUrl={url}&jtss=tianya&ccBody=",
"msn" :"http://profile.live. com/P.mvc#!/badge?url={url}&screenshot=",
"douban" :"http://shuo.douban.com/!service/share?image=&href={url}&name ={title}",
"twangyi" :"http://t.163.com/article/user/checkLogin.do?source={title}&info={title} {url}&images=",
"mop" :"http://tk.mop.com/api/post.htm?url={url}&title={title}"
};
var shareiconame = {
" tqq" :"Tencent Weibo",
"tsina" :"Sina Weibo",
"qzone" :"QQ Space",
"renren" :"Renren",
"baidu" :"Baidu Collection",
"115" :"115",
"tsohu" :"Sohu Weibo",
"taobao" :"Taojianghu",
"xiaoyou " :"Tencent Friends",
"hi" :"Baidu Space",
"fanfou" :"Fanfou",
"sohubai" :"Sohu Baixie",
"feixin" :"Fetion",
"tianya" :"Tianya Community",
"youshi" :"Youshi.com",
"msn" :"MSN",
"douban" :"Douban ",
"twangyi" :"NetEase Weibo",
"mop" :"Maopu Tike"
};

The first array is very clear, it is the link address corresponding to each share button. I replaced the title and url with {title} and {url}, and then replaced it through regular expressions during loop binding. Lose. The second array corresponds to their respective Chinese names and is used to display the title of each button on the front desk, such as: share to Tencent Weibo, share to Sina Weibo, etc.
Since js does not have the concept of multi-dimensional arrays, I defined a 2-array. Next is the js code implementation part (in order to serve as a tutorial, I wrote some parameters directly to make it easier for everyone to understand).
Copy code The code is as follows:

$("div").addClass("hr- share-16");
var title = document.title;
var url = window.location.href;
function eFunction(str){
return function(){
window. open(formatmodel(shareico[str],{title:title, url:url}));
}
}
for(si in shareico){
$(".hr-share- " si).die('click').live('click',eFunction(si)).attr("title","Share to" shareiconame[si]);
}

Here, I first added a class style to the outermost div container, which is the one I mentioned above. After executing this code, you will find that the styles of the buttons on the page are displayed.
Next, I obtained the title and link of the current page through document.title and window.location.href respectively. Then there is a method called eFunction. I will skip this and will talk about it later.
The following is a for loop, which realizes the effect of loop binding click events. Two points need to be noted here: First, because I am writing it as a plug-in, the share button may be used in more than one place on the page. In order to prevent repeated event binding, I use die to unbind each event before binding; Second, I use live instead of bind because I am worried that the sharing plug-in in some projects may be loaded through ajax after the page is loaded, so I bind it directly with live.
Let’s talk about the eFunction issue again. Some people will definitely ask why the content in the eFunction is not written directly in the live click event. In fact, I did this at the beginning, but the reason why I didn't do this was very simple. I couldn't pass custom parameters in. As for why, I asked some JS experts and it was a closure issue. I wasn’t very clear about this, so I found a way to solve it. If anyone can explain the closure problem to me in detail, I would be very grateful.
There is also a formatmodel method in the binding event. This is for replacement. As I said above, use regular expressions to replace {title} and {url}. You can refer to this function and learn it. It can be used In many places:
Copy code The code is as follows:

function formatmodel(str,model){
for(var k in model){
var re = new RegExp("{" k "}","g");
str = str.replace(re,model[k]);
}
return str;
}

After this step, everything is OK. Some people may ask why the "more" button is not mentioned. In fact, it has nothing to do with js. It is just the display effect of html css. The event binding is still the core code above. If you are interested, you can download my entire Check the plug-in source code. The plug-in is free and open source and can be modified at will, but please keep the author and contact information.
View the complete plug-in address: Click to enter
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 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.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 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.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 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.

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

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 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.

See all articles