欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

点星星代码实现

程序员文章站 2022-05-18 09:14:32
点星星代码实现 ...

点星星代码实现

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>  
        <style>  
            body,ul,li{  
                padding:0;  
                margin:0;  
            }  
            li {  
                list-style-type: none;  
            }  
            .rating {  
                width: 130px;  
                height: 26px;  
                margin: 100px auto;  
            }  
            .rating-item {  
                float: left;  
                width: 26px;  
                height: 26px;  
                background: url(star1.png) no-repeat center;  
            }  
        </style>  
</head>  
<body>  
    <ul class="rating" id="rating">  
        <li class="rating-item" title="很不好"></li>  
        <li class="rating-item" title="不好"></li>  
        <li class="rating-item" title="一般"></li>  
        <li class="rating-item" title="好"></li>  
        <li class="rating-item" title="很好"></li>  
    </ul>  
    <ul class="rating" id="rating2">  
        <li class="rating-item" title="很不好"></li>  
        <li class="rating-item" title="不好"></li>  
        <li class="rating-item" title="一般"></li>  
        <li class="rating-item" title="好"></li>  
        <li class="rating-item" title="很好"></li>  
    </ul>  
  
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>  
    <script>  
    var rating=(function(){  
        // 点亮  
            var init=function(el,num){  
                var $rating =$(el),  
                    $item=$rating.find('.rating-item');  
                var lightOn=function($item,num){  
                    $item.each(function(index){  
                    if(index<num){  
                    $(this).css('background-image','url(star2.png)');  
                    }else{  
                    $(this).css('background-image','url(star1.png)');  
                    }  
                });  
            };  
                            // 初始化  
                lightOn($item,num);  
                // 事件绑定  
                $rating.on('mouseover','.rating-item',function() {  
                    lightOn($item,$(this).index()+1); //加一是因为上面是小于  
                }).on('click','.rating-item',function(){  
                    num=$(this).index()+1; //直接改变num值  
                }).on('mouseout',function(){  //离开时显示  
                    lightOn($item,num);  
                });       
            };  
            // jq封装  
            $.fn.extend({  
                rating:function(num){  
                    return this.each(function(){  
                        init(this,num);  
                    });  
                }  
            })  
            return {  
                init:init  
            };  
  
    })();  
    $('#rating').rating(1);  
    $('#rating2').rating(4);  
    </script>  
</body>  
</html>