Home > Web Front-end > CSS Tutorial > How Can I Dynamically Generate Star Ratings from Numerical Input Using jQuery and CSS?

How Can I Dynamically Generate Star Ratings from Numerical Input Using jQuery and CSS?

Susan Sarandon
Release: 2024-12-14 15:39:21
Original
805 people have browsed it

How Can I Dynamically Generate Star Ratings from Numerical Input Using jQuery and CSS?

Transforming Numbers into Star Rating Displays Using jQuery and CSS

In the realm of displaying ratings, transforming numerical values into star ratings is a common challenge. How can we dynamically generate star ratings based on numerical input using jQuery and CSS?

Solution:

Here's an innovative solution that leverages a single image and CSS:

CSS


<br>span.stars, span.stars span {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">display: block;
background: url(stars.png) 0 -16px repeat-x;
width: 80px;
height: 16px;
Copy after login

}

span.stars span {

background-position: 0 0;
Copy after login

}

Image:


A single image (stars.png) with yellow stars at the top and gray stars at the bottom.

jQuery:


<br>$.fn.stars = function() {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">return $(this).each(function() {
    var val = parseFloat($(this).html());
    var size = Math.max(0, (Math.min(5, val))) * 16;
    var $span = $('<span />').width(size);
    $(this).html($span);
});
Copy after login

}

HTML:


<br><span><span class="stars">2.6545344</span><br><span><span class="stars">8</span><br>

Usage:


<br>$(function() {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$('span.stars').stars();
Copy after login

});

Output:


This solution uses CSS sprites to combine both yellow and gray stars into a single image, allowing us to control the width of the yellow stars to represent the desired rating.

Advantages:

The above is the detailed content of How Can I Dynamically Generate Star Ratings from Numerical Input Using jQuery and CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Previous article:How Can I Create Multi-Column Lists with CSS? Next article:How Can I Set an Element's Height to 100% Minus a Fixed Pixel Value?
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template