Home > Web Front-end > JS Tutorial > body text

jQuery plug-in-jRating rating plug-in source code analysis and usage_jquery

WBOY
Release: 2016-05-16 17:44:50
Original
1153 people have browsed it

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 two< div>Coincident
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!
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template