html 星星評分源碼

css

.tip-word{margin-left:20px;color:red;}
.stars{margin: 8px;height:20px;}
.stars span{ float: left; line-height: 15px; }
.stars i{width: 15px; height: 15px; line-height: 15px; float: left; margin-right: 5px;background-position:center; background-image:url(images/star_gray.png);background-size: 100%; color: #fff; text-align: center; cursor:Pointer; font-style: normal;}
.stars .on{background-image:url(images/star.png);background-position:center;background-size: 100%;}

html

<div class="stars">
    <span>評價:</span>
    <for start="0" end="5" comparison="lt" step="1" name="i" >
        <i class="on"></i>
    </for>
    <span class="tip-word">非常好</span>
    <input id="point" type="hidden" name="point" value="5"/>
</div>

JS

<script>
    $(function(){
        /*
        * 鼠標點擊,該元素包括該元素之前的元素獲得樣式,并給隱藏域input賦值
        * 鼠標移入,樣式隨鼠標移動
        * 鼠標移出,樣式移除但被鼠標點擊的該元素和之前的元素樣式不變
        * 每次觸發事件,移除所有樣式,并重新獲得樣式
        * */
        var tip_word = ["非常差","差","一般","好","非常好"];
        var stars = $('.stars');
        var Len = stars.length;
        //遍歷每個評分的容器
        for(i=0;i<Len;i++){
            //每次觸發事件,清除該項父容器下所有子元素的樣式所有樣式
            function clearAll(obj){
                obj.parent().children('i').removeClass('on');
            }
            stars.eq(i).find('i').click(function(){
                var num = $(this).index();
                clearAll($(this));
                //當前包括前面的元素都加上樣式
                $(this).addClass('on').prevAll('i').addClass('on');
                //給隱藏域input賦值
                $(this).siblings('input').val(num);
                //文字提示
                $(this).siblings('.tip-word').html(tip_word[num-1]);
            });
            stars.eq(i).find('i').mouseover(function(){
                var num = $(this).index();
                clearAll($(this));
                //當前包括前面的元素都加上樣式
                $(this).addClass('on').prevAll('i').addClass('on');
                //文字提示
                $(this).siblings('.tip-word').html(tip_word[num-1]);
            });
            stars.eq(i).find('i').mouseout(function(){
                clearAll($(this));
                //觸發點擊事件后input有值
                var score = $(this).siblings('input').val();
                //默認最少一個
                if (score == 0)score = 1;
                //文字提示
                $(this).siblings('.tip-word').html(tip_word[score-1]);
                //當前包括前面的元素都加上樣式
                for(i=0;i<score;i++){
                    $(this).parent().find('i').eq(i).addClass('on');
                }
            });
        }
    })
</script>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容