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
Susan SarandonOriginal
2024-12-14 15:39:21869browse

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>
<pre class="brush:php;toolbar:false">display: block;
background: url(stars.png) 0 -16px repeat-x;
width: 80px;
height: 16px;

}

span.stars span {

background-position: 0 0;

}

Image:


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

jQuery:


<br>$.fn.stars = function() {</p>
<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);
});

}

HTML:


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

Usage:


<br>$(function() {</p>
<pre class="brush:php;toolbar:false">$('span.stars').stars();

});

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:

  • Simple and lightweight.
  • Supports fractional star ratings.
  • Utilizes CSS to control the appearance of the stars.

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!

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