三种等级星星投票实现方式

一、传统的DOM操作

  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style style="text/css">
        #vote div {
            position: relative;
            float: left;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="voteed">选取:</div>
    <div id="vote">
        <div>☆</div>
        <div>☆</div>
        <div>☆</div>
        <div>☆</div>
        <div>☆</div>
    </div>
    <script type="text/javascript">
        window.onload = function() {
            function getTypeElement(es, type) {
                var esLen = es.length,
                    i = 0,
                    eArr = [],
                    esi = null;
                for (; i < esLen; i++) {
                    esl = es[i];
                    if(esl.nodeName.replace("#", "").toLocaleLowerCase() === type) {
                        eArr.push(esl);
                    }
                }
                return eArr;
            }
            function vote(e) {
                var votes = getTypeElement(e.childNodes, "div"),
                        i = 0,
                        m = null,
                        k = 0,
                        n = 0,
                        allnum = 5,
                        voteed = document.getElementById("voteed");
                for (; i < allnum; i++) {
                    m = votes[i];
                    m.setAttribute("data-num", i);
                    m.onmouseover = function() {
                        k = 0;
                        n = parseInt(this.dataset.num, 10);
                        voteed.innerHTML = "选取" +(n + 1)+ "星级";
                        for (; k < allnum; k++) {
                            var v = votes[k];
                            v.innerHTML = parseInt(v.getAttribute("data-num"), 10) <= n ? "★" : "☆";
                        }
                    }
                }
            }
            vote(document.getElementById("vote"));
        };
    </script>
</body>
</html>

 2、使用VUE等框架实现

  

<div class="score-bar">
<label class="score" v-for="n in 5" :class="{checked: n < form.score}">
<input type="radio" name="score" value="{{1+n}}" v-model="form.score">
</label>
</div>
.score-bar {
width: 140px;
margin: 0 auto;
overflow: hidden;
> .score {
float: left;
width: 28px;
height: 28px;
background: url(../assets/star.png) repeat-x scroll left center;
background-size: auto 100%;
}
> .checked {
background: url(../assets/star-light.png) repeat-x scroll left center;
}
}
.score > input[type="radio"] {
-webkit-appearance: none;
appearance: none;
visibility: hidden;
}

3、CSS方式实现

  http://www.zhangxinxu.com/wordpress/2013/08/%E7%BA%AFcss%E6%98%9F%E6%98%9F%E8%AF%84%E5%88%86%E4%BA%A4%E4%BA%92-%E5%85%84%E5%BC%9F%E9%80%89%E6%8B%A9%E5%99%A8/

  参照这位大神的博客,我就不复制了。

posted @ 2016-09-05 14:34  林小新新  阅读(242)  评论(0)    收藏  举报