jquery实现仿商品星级评价

时间:2023-03-09 07:59:22
jquery实现仿商品星级评价
一,HTML部分
<div id="rating-star">
    <a href="#">0</a>
    <a href="#">1</a>
    <a href="#">2</a>
    <input type="hidden" id="goodLevel" />
</div>
二,CSS部分
接着给rating-star和链接一个样式,切换图片的关键只需要修改background-position就可以了:
#rating-star {
    margin: 50px;
}
    #rating-star a {
        background: url(commentstar.png) no-repeat 0 -90px;
        display: inline-block;
        height: 23px;
        text-indent: -999em;
        width: 23px;
    }
三,Js代码部分(关键的脚本)

$('#rating-star').on('click', 'a', function () {
    $('#goodLevel').val(this.innerHTML);
}).on('mouseenter', 'a', function () {
    setStar(this);
}).on('mouseleave', 'a', function () {
    var level = $('#goodLevel').val();
    var $stars = $('#rating-star > a');
    if (level == '') {
        $stars.css('background-position', '0 -90px');
    } else {
        setStar($stars[level]);
    }
});
function setStar(star) {
    var $this = $(star);
    var level = $this.html();
    var n;
    if (level == '2') {
        n = '0 -30px';
    } else if (level == '1') {
        n = '0 0';
    } else {
        n = '0 -60px';
    }
    $this.prevAll().andSelf().css('background-position', n);
    $this.nextAll().css('background-position', '0 -90px');
}