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?
Here's an innovative solution that leverages a single image and 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;
}
span.stars span {
background-position: 0 0;
}
<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); });
}
<br><span><span class="stars">2.6545344</span><br><span><span class="stars">8</span><br>
<br>$(function() {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$('span.stars').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!