search
HomeWeb Front-endJS TutorialjQuery plug-in-jRating rating plug-in source code analysis and usage_jquery

This plug-in is widely used in various pages that need to be scored. Today, as a study, I will take out the source code and analyze it, and learn how to use it.
1. Overview of plug-in usage.

Copy code The code is as follows:


An example




Copy code The code is as follows:






Execution effect:

As you can see, in the above example, there are 10 stars, which is the parameter length role. Among them, the default total score is 20 points, that is, all 10 stars are selected. Here we focus on the id16_1 of
, where 16 is used to initialize the default ratio selected by the scoring plug-in, 16/20 * 10. So we have 8 stars above that are yellow.

When we put the mouse on the plug-in, the small stars will increase or decrease as the mouse moves (red will cover yellow or white), indicating a rating from 0 to 20, but when the mouse is clicked, the rating At the end, the plug-in can no longer be edited. At the same time, POST data to the specified path through Ajax, and use background data to persist the rating data.

Before analyzing the source code, let’s take a look at the optional parameters when using the plug-in:

2. Plug-in source code analysis

According to the recommended method for jQuery plug-in development, in order to avoid the shortcut symbol "$" from conflicting with other JavaScript plug-ins, the following technology is used at the beginning of the source code:
Copy code The code is as follows:

(function($) {
$.fn.jRating = function(op) {
//Here is the plug-in code
}
})(jQurery)

Next, all the code we analyze will appear in the green area above, first set the default parameters.
Copy code The code is as follows:

var defaults = {
/**String vars **/
bigStarsPath : 'icons/stars.png', // Set the relative path of big stars (displayed by default)
smallStarsPath : 'icons/small.png', // Small stars
phpPath : 'php/jRating.php', // Click the mouse. After the rating is confirmed, the address of the POST data will be processed using ASP.Net technology.
type: 'big', // As can be seen, the default It uses big stars
/**Boolean vars **/
step:false, // If set to True, the stars will either completely change color or not completely. Of course, this is also suitable for synchronization with the selection score.
isDisabled:false, //If set to True, the plug-in cannot be edited. When the mouse is clicked, the default state is True
showRateInfo: true, //When the mouse is placed on the star, whether it is under the mouse Display the selection ratio information, such as 16/20
/**Integer vars **/
length:5, // The number of stars
decimalLength : 0, // The decimal places after the selected number , up to 3 digits. If set to 1, the possible situation is 16.3/20
rateMax : 20, // Denominator in the ratio, integer 0-9999
rateInfosX : -45, // Information prompt box Abscissa position relative to the mouse position
rateInfosY: 5, // Same as above, ordinate position
/**Functions **/
onSuccess: null, //Callback function after success
onError: null //Error handling function
};

Through the explanation in the green part above, we can see the default values ​​​​of all parameters. At the same time, we can use the plug-in according to needs Determine the appropriate configuration. Isn’t the use of plug-ins just a combination of these parameters?
Next let’s look at a function scope:
Copy the code The code is as follows:

if(this.length>0)
return this.each(function() { //The code that appears next will be here!!!}

This code is very simple. We need to execute the jRating() function on the selected collection. The above code first determines whether the length of the collection is greater than 0. If it is 1 or more, execute each() on the collection. Function, each element (div) in the collection is processed individually.
The core code of this plug-in is actually in the each() function above. Let’s first look at a few functions. These functions are all defined in each. () function, and is called by other statements
Copy code The code is as follows: findRealLeft(obj) { if( !obj ) return 0; return obj.offsetLeft findRealLeft( obj.offsetParent );
};


First focus on the findRealLeft() function , this function receives an object parameter named obj, and finally returns the distance of the element object relative to the left border of the browser. Note: offsetParent refers to the element's nearest positioned (relative, absolute) ancestor element. If no ancestor element is positioned, Will point to the body element. offsetLeft returns the position relative to offsetParent.

Copy code

The code is as follows: >function getNote(relativeX) {
var noteBrut = parseFloat((relativeX*100/widthRatingContainer)*opts.rateMax/100); //Can the two 100s be removed to indicate the selected ratio, such as 16 or 16.1
switch(opts.decimalLength) { //Determine the number of decimal places required to lose the proportion according to the parameters, for example, 16.1 16.12 16.123 case 1: var note = Math.round(noteBrut*10)/10; break; case 2 : var note = Math.round(noteBrut*100)/100; break;
case 3 :
var note = Math.round(noteBrut* 1000)/1000;
break;
default :
var note = Math.round(noteBrut*1)/1;
}
return note;
};


Next, focus on the getNote function. First, let’s look at what relative


var realOffsetLeft = findRealLeft(this);
var relativeX = e.pageX - realOffsetLeft;


The above two lines of code define relativeX before calling the getNote function. For variables, we can analyze the role of relativeX. This here is a certain div where we apply the jRating() function, and first obtain its left margin relative to the browser, because the above two lines of code appear in the mouse movement processing function mouseenter (we will see it later), so e.pageX here represents the horizontal distance of the mouse relative to the browser. Therefore, relativeX here represents the horizontal distance of the mouse relative to the left border of
.
We pay attention to the getNote function again. From widthRatingContainer = starWidth*opts.length, we can see that widthRatingContainer is the combined width of the left and right star images. Therefore, var noteBrut = parseFloat((relativeX*100/widthRatingContainer)*opts.rateMax/100); you can remove the two 100s in the denominator and numerator, that is, (relativeX/widthRatingContainer)*opts.rateMax), and the noteBrut variable is finally stored is the ratio of mouse selection. If rateMax is set to 20, the range of noteBrut can be determined by the mouse (0-20).
The switch function uses the decimalLength parameter (used to set the decimal digits of the display ratio) to ultimately determine the number of digits (ratio) displayed. After reading this, we can find that the getNote function returns the mouse selection ratio through relativX. What is this ratio? See the part framed with a brush in the picture below:


Copy the code


The code is as follows:


function getStarWidth(){
switch(opts.type) {
case 'small' : starWidth = 12; // width of small.png small star image starHeight = 10 ; // Height bgPath = opts.smallStarsPath; // Image relative address
break; default : starWidth = 23; // The width of the big star, as you can see, this is the default value
starHeight = 20; //Height
bgPath = opts.bigStarsPath; //Relative address of star image} };
This is a relatively simple function for initializing variables. According to the type attribute, three variables are initialized, namely starWidth, starHeight, and bgPath. The green annotation information can explain everything, so I won’t go into details!
After reading the functions defined in each(), next, we are still wandering in the each() function. In order from top to bottom, we first intercepted a few lines of code as follows:
Copy code The code is as follows:

var opts = $.extend(defaults, op), //Use the extend() function Merge the default parameters with the input parameters, and finally store them in the opts variable.
newWidth = 0, //Define a variable, which is used to store relativeX, but will be adjusted accordingly according to the step attribute
starWidth = 0, //Define a variable, the width of the star
starHeight = 0, / /Height
bgPath = ''; //Star image address
if($(this).hasClass('jDisabled') || opts.isDisabled) //Determine the jDisabled variable, indicating whether the div can be operated
var jDisabled = true;
else
var jDisabled = false;
getStarWidth(); //This function will not be described in detail, it has been analyzed above
$(this).height(starHeight); //Determine the height of this div based on the height of the star.

Then look down:
Copy the code The code is as follows:

var average = parseFloat($(this).attr('id').split('_')[0]), //By the id of
(for example, 16_2), Get the number before the underscore and use this number as the default selection ratio
idBox = parseInt($(this).attr('id').split('_')[1]), // The part after the underscore , as the id of the identification rating plug-in
widthRatingContainer = starWidth*opts.length, // The sum of the widths of the star images, and as the width of the surrounding container
widthColor = average/opts.rateMax*widthRatingContainer, // occupied by the color block Width

Next, we will see the three newly created
inserted into the main div
Copy code The code is as follows:

quotient =
$('
',
{
'class' : 'jRatingColor',
css:{
width:widthColor
}
}).appendTo($(this)),
average =
$('
',
{
'class' : 'jRatingAverage',
css:{
width:0,
top:- starHeight
}
}).appendTo($(this)),
jstar =
$('
',
{
'class' : 'jStar',
css:{
width:widthRatingContainer,
height:starHeight ,
top:- (starHeight*2),
background: 'url(' bgPath ') repeat-x'
}
}).appendTo($(this));

First we analyze the first
, its class name is jRatingColor, which represents the default ratio, expressed in yellow, and its length is withColor. Here we mainly look at its style sheet:
Copy code The code is as follows:

.jRatingColor {
background-color:#f4c239; / * bgcolor of the stars*/
position:relative; //Relative positioning
top:0;
left:0;
z-index:2; //It should be noted here that the div The ancestor is the z-index of this in our each function is 1, as we will see soon.
height:100%;
}

The second
style sheet is as follows:
Copy code The code is as follows:

.jRatingAverage {
background-color:#f62929; //Red
position:relative;
top:0;
left:0;
z-index:2;
height:100%;
}

But in the above program, when initializing, the width is set It is 0 (because the mouse has not selected it yet), and the top value is changed at the same time: - the star height, so that it coincides with the div added above in the vertical direction.
Next, look at the third
, which is mainly used to place small stars.
Copy the code The code is as follows:

/**Div containing the stars **/
. jStar {
position:relative;
left:0;
z-index:3;
}

This style sheet is relatively simple, let’s focus on the JS Several dynamically added attribute values:
Copy code The code is as follows:

width:widthRatingContainer, //Set the width
height:starHeight, //Height
top:- (starHeight*2), //Change the vertical value, and the above twoCoincident
background: 'url(' bgPath ') repeat-x' //Set the background to the little star
The value of the
attribute is set, but some people may ask, why only See that the little stars are colored, and the first two
added above are not rectangular color bars with height? Let’s take a look at the picture of Little Star below and you’ll understand why!

Needless to say, use an opaque background next to it, the little star in the middle is transparent, and the color below will naturally show through! !
The next statement is very simple, just set the style of the outermost div container, pay attention to the z-Index attribute:
Copy code The code is as follows:

$(this).css({width: widthRatingContainer,overflow:'hidden',zIndex:1,position:'relative'});

Next we will enter the relatively complicated part. We will focus on mouse actions and their response effects. First, we will focus on a small logic:
if(!jDisabled)
//The next code
can It can be seen that the jDisable variable we set earlier is used here. If jDisabled is true, it means that the plug-in is disabled, then the next mouse operation will not be performed.
Let’s see how mouse operations are added to the plug-in:
$(this).unbind().bind({//Mouse event processing code, which will be discussed separately below.
});
First look at the mouse entry event handling code:
Copy the code The code is as follows:

mouseenter : function(e){
var realOffsetLeft = findRealLeft(this);
var relativeX = e.pageX - realOffsetLeft; //First calculate relativeX, which represents the mouse relative Horizontal distance from the left border of the outer

if (opts.showRateInfo)
var tooltip =
$('

',{
'class' : 'jRatingInfos' ,
html : getNote(relativeX) ' / ' opts.rateMax '', //Note that the getNote method is used here, its purpose has been explained before .
css: {
top: (e.pageY opts.rateInfosY),
left: (e.pageX opts.rateInfosX)
}
}).appendTo('body') .show();
},


The relative To display proportion information (for example, 16/20 is displayed under the mouse), the tooltip variable is this information box, and is finally added to the body through the appendTo method. The code logic is very simple. This function is mainly used to display the prompt box

. Here we can focus on the style of the

node. It is absolutely positioned and uses the code to change the top and Left values. See Here is the relevant style sheet:

Copy code The code is as follows:

p.jRatingInfos {
position: absolute;
z-index:9999;
background: transparent url('http://www.cnblogs.com/icons/bg_jRatingInfos.png') no-repeat;
color: # FFF;
display: none;
width: 91px;
height: 29px;
font-size:16px;
text-align:center;
padding-top:5px;
}
p.jRatingInfos span.maxRate {
color:#c9c9c9;
font-size:14px;
}

Next we look at the mouse The handler function of the mousemove event after coming in:
Copy code The code is as follows:

mousemove: function (e){
var realOffsetLeft = findRealLeft(this);
var relativeX = e.pageX - realOffsetLeft;
if(opts.step) newWidth = Math.floor(relativeX/starWidth)*starWidth starWidth;
else newWidth = relativeX;
average.width(newWidth);
if (opts.showRateInfo)
$("p.jRatingInfos")
.css({
left: (e.pageX opts.rateInfosX)
})
.html(getNote(newWidth) ' / ' opts.rateMax '');
},

This function is mainly used to determine the proportion of mouse selection. Of course, this proportion is obtained through getNote(newWidth). Then, determining the appropriate newWidth value becomes the core of this function. If opts.step is true, that is The ratio can only be an integer number of stars (cannot be 15.3, etc.), then let's take a look at this logic: Math.floor(relativeX/starWidth), starWidth is the width of the star picture, Math.floor(-0.1)=-1, Math .floor(0.1) = 0, Math.floor(2.6)=2, knowing these, the code in red above is easy to understand.
OK, let's go on, let's take a look at three simple processing functions
Copy the code The code is as follows:

mouseover : function(e){
$(this).css('cursor','pointer');
},
mouseout : function(){
$( this).css('cursor','default');
average.width(0);
},
mouseleave: function () {
$("p.jRatingInfos"). remove();
},

The mouseover function ensures the display style after the mouse enters the plug-in. The same is true for mouseout, but it changes the width of the div (red) with the class name average to 0 , the mouseleave function makes the prompt message box disappear.
The last function is also the end of the entire source code, and of course the most important and complex one - the mouse click function:
Copy code The code is as follows:

click : function(e){
//The following codes are here.
}

Let’s split up and look at the first part first:
Copy code Code As follows:

$(this).unbind().css('cursor','default').addClass('jDisabled');

Why is this only List a statement, because it is very important, but also very simple. We must pay attention to the unbind() function here. It is very, very important. When the mouse is clicked, first all other events bound to the peripheral
Removed, so that the appearance of the plug-in will be fixedly displayed in the browser the moment the mouse is clicked, and will no longer change with mouse events. Of course, finally add the jDisabled attribute to
.
Let’s go back:
Copy the code The code is as follows:

if (opts .showRateInfo) $("p.jRatingInfos").fadeOut('fast',function(){$(this).remove();});
e.preventDefault();
var rate = getNote (newWidth); //Pay attention to the rate variable, which will be used later.
average.width(newWidth);

The first sentence is not difficult to understand. Delete the prompt message box. The second sentence cancels the default operation of mouse click. The last two sentences are very simple and will not be repeated. , you must know that newWidth has been mentioned before, indicating the width of mouse selection.
The last statement sends the selected ratio to the server for persistence:
Copy code The code is as follows:

$.post(
opts.phpPath, //Use Ajax technology to send data to the server address
{ //Post past data
idBox : idBox,
rate : rate,
action : 'rating'
},
function(data) { //Callback function, mainly passes parameters to the plug-in custom function and executes it. .error)
{
if(opts.onSuccess) opts.onSuccess( element, rate );
}
else
{
if(opts.onError) opts.onError( element, rate );
}
},
'json' //Determine how to understand the returned data, it uses json.
);


Using jQuery to do Ajax is indeed very simple. Necessary comments have been made in the code. I won’t go into details here. The source code of this plug-in has been analyzed. It is relatively rough, but the whole logic may reflect some of it. I hope this study note can be useful to everyone. help. Now we enter the practical stage.
3. Practical jRating plug-in
In order to be closer to the real application, we first use sql server to create a database table, which is an article type table with id, title, article content, and rating Four fields, screenshots are as follows:

The rating field defaults to -1, indicating that the article has not been rated yet. Of course, some people will now say that the design of this table is very unreasonable, because an article will not be rated only once. Every user should be able to comment. Yes, we are here just to demonstrate that the jRating plug-in uses Ajax for persistence. Since it is a demonstration operation, everything should be done frugally.
Create a new Web page to display the title, content and rating plug-in of the first article (id 1), see the front-end code:
Copy code The code is as follows:






















The background CS code is as follows:
Copy the code The code is as follows:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
tempEntities cbx = new tempEntities(); //Used Entity Framework to obtain the data table
var page1 = cbx.jRatingArticles.Where(m => m.id == 1).SingleOrDefault();
page1_title.Text = page1.title;
page1_body.Text = page1.body;
}
}

In order to reduce the database connection code, I used Entity Framework, Only one table (jRatingArticle) is mapped, which is what we see above. Get the article object with id 1, and assign the corresponding properties to the Text property of the Label control.
The page effect is as follows:

We can see that in the JS code of the front page above, there is such a statement:
phpPath: 'tempAjax.aspx/UpdateComment '
It specifies the address to send data through Ajax when the mouse clicks on the plug-in. Here we use .net page technology to handle this asynchronous request. The background cs code of tempAjax.aspx is as follows:
Copy code The code is as follows:

[WebMethod( )]
public static void UpdateComment(int idBox, int rate)
{
tempEntities cbx = new tempEntities();
var page1 = cbx.jRatingArticles.Where(m => m.id == 1).SingleOrDefault();
page1.is_comment = rate;
cbx.SaveChanges();
}

At this time, we also need to modify the jRating plug-in In the original file, replace the $.post function in the mouse click (click) processing function as follows:
Copy code The code is as follows:

$.ajax({
type: "POST",
url: opts.phpPath,
data: '{"idBox":"' idBox '","rate": "' rate '"}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});

Why? Change the source file because I want to change the contentType attribute of the Ajax request and send the request data in json format. The default is application/x-www-form-urlencoded
OK. Everything is ready. Let’s take a look at the execution effect (the selection ratio is 16 , 16 red stars):

Look at the changes in the database:

Test success! That’s it for today’s study. I hope this study note can be helpful to everyone!
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
atom中 40+ 个常用插件推荐分享(附插件安装方法)atom中 40+ 个常用插件推荐分享(附插件安装方法)Dec 20, 2021 pm 04:14 PM

本篇文章给大家分享40+ 个atom常用插件,并附上在atom中安装插件的方法,希望对大家有所帮助!

五个IntelliJ IDEA插件,高效编写代码五个IntelliJ IDEA插件,高效编写代码Jul 16, 2023 am 08:03 AM

人工智能AI是当前广受认可的未来趋势和发展方向。虽然有些人担心AI可能会取代所有的工作,但实际上只会取代那些重复性高、产出低的工作。因此,我们应该学会更加聪明地工作,而不是使劲努力地工作。本文介绍5个由AI驱动的Intellij插件,这些插件可以帮助你提高生产力,减少繁琐的重复性工作,让你的工作更加高效、便捷。1GithubCopilotGithubCopilot是由OpenAI和GitHub联合开发的一款人工智能代码辅助工具。它使用了OpenAI的GPT模型来分析代码上下文,预测并生成新的代码

vscode插件分享: 6个Vue3开发必备插件vscode插件分享: 6个Vue3开发必备插件Dec 09, 2022 pm 08:36 PM

本篇文章给大家整理分享 6 个 Vue3 开发必备的 VSCode 插件,可以直接用过 VSCode 的插件中心直接安装使用,希望对大家有所帮助!

用 VSCode 写 Python,这14个插件不容错过!用 VSCode 写 Python,这14个插件不容错过!May 24, 2023 pm 05:19 PM

可以说,VisualStudioCode这个编辑器,让微软在开源社区赢回了王者段位,要知道全球2400万开发者中有1400万称VSCode为自己的家,再加上GitHub和VSCode的结合,几乎所有的程序员的都离不开VSCode,不过,VSCode如此优秀,值得每个程序员使用,甚至我觉得非程序员都可以用它来码字。如果你还没用过VSCode,那访问这里安装[1]一个吧,很可能就打开了一个新世界。今天分享14个非常实用VSCode插件,可以让你写代码如同神一般,尤其是

2023年最新最全的VScode插件推荐2023年最新最全的VScode插件推荐Jan 24, 2023 am 05:30 AM

这篇文章主要介绍了这么多年来我在使用 VSCode 过程中用到的一些不错的插件。这些VSCode插件,帮你打造地表最强IDE!

【吐血总结】23个VSCode 插件,助你提高开发效率和美观性【吐血总结】23个VSCode 插件,助你提高开发效率和美观性Mar 10, 2022 pm 08:01 PM

本篇文章给大家总结了23个各种功能的VSCode 插件,可以帮助开发者提高开发效率和美观性,希望对大家有所帮助!

今年高考作文题目,我用AI写了两篇,大伙看看打几分?今年高考作文题目,我用AI写了两篇,大伙看看打几分?Jun 08, 2023 am 11:48 AM

今年高考作文题目,我用AI写了两篇,大伙看看打几分?#假如AI来写高考作文#高考作文题目出来了,有人说比去年简单,也有人说题目起得很贴热点,但今天不说这些,咱们要搞点新鲜的。这段时间,AI技术很火,很多人对人工智能有了新的认识。那么就给大家用AI去写这次高考的作文题目。由于时间篇幅有限,只能做个截取,我只念这些文章的开头部分,给大家看看。看大家能给打多少分。全国甲卷的作文题目是:人们因技术发展得以更好地掌控时间,但也有人因此成了时间的仆人。这句话引发了你怎样的联想与思考?请写一篇文章。看看AI

浏览器增强版ChatGPT无敌了?超强插件Monica,能聊能写效率Max浏览器增强版ChatGPT无敌了?超强插件Monica,能聊能写效率MaxMay 03, 2023 pm 06:58 PM

提起Monica,你会想到什么?是老友记里的主角之一Monica·Geller,一个热心肠的女主人形象;还是心跳文学部里的疯疯癫癫的Monika?或者,最近爆火的Chrome插件——Monica。它的功能实在是太强大了,用完一次保你爱不释手。毕竟,搭载了ChatGPT的网页助手,能是俗物吗?Monica功能大赏首先明确一点,Monica是ChatGPT在网页上的应用,换句话说,Monica就是靠着ChatGPTAPI的强大功能才厉害。而仔细看看Chrome商店中的介绍,我们就会发现Monica真

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),