【学艺不精系列】简单的 JavaScript 表示星级的页面控件脚本

效果图:

效果图

表单名称:Importance,类型为字符串,默认值 '☆☆☆☆☆'

使用方法:

引用此脚本,为容器设置id='selStar',容器最好是span,放在页面需要的位置。

JavaScript脚本:

/// <reference path="jquery-1.4.1.js" />

/// <reference path="jquery-1.4.1-vsdoc.js" />



$().ready(function () {

    $("#selStar").css("cursor", "pointer");

    $("#selStar").html('<span id="star0">☆</span><span id="star1">☆</span><span id="star2">☆</span><span id="star3">☆</span><span id="star4">☆</span>'

        + '<input type="hidden" name="Importance" id="importance" value="☆☆☆☆☆" />');



    var s0 = 0; var s1 = 0; var s2 = 0; var s3 = 0; var s4 = 0;



    $("#star0").mouseover(function () { s0 = 1; fnStar(); });

    $("#star1").mouseover(function () { s1 = 1; fnStar(); });

    $("#star2").mouseover(function () { s2 = 1; fnStar(); });

    $("#star3").mouseover(function () { s3 = 1; fnStar(); });

    $("#star4").mouseover(function () { s4 = 1; fnStar(); });



    $("#star0").mouseout(function () { s0 = 0; fnStar(); });

    $("#star1").mouseout(function () { s1 = 0; fnStar(); });

    $("#star2").mouseout(function () { s2 = 0; fnStar(); });

    $("#star3").mouseout(function () { s3 = 0; fnStar(); });

    $("#star4").mouseout(function () { s4 = 0; fnStar(); });



    $("#star0").click(fnClick);

    $("#star1").click(fnClick);

    $("#star2").click(fnClick);

    $("#star3").click(fnClick);

    $("#star4").click(fnClick);



    function fnStar() {

        if (s0 + s1 + s2 + s3 + s4 == 0) {

            var s = $("#importance").val().split('');

            $("#star0").text(s[0]); $("#star1").text(s[1]); $("#star2").text(s[2]); $("#star3").text(s[3]); $("#star4").text(s[4]);

        } else {

            $("#star0").text("☆");

            $("#star1").text("☆");

            $("#star2").text("☆");

            $("#star3").text("☆");

            $("#star4").text("☆");

            if (s0 + s1 + s2 + s3 + s4 > 0) { $("#star0").text("★"); }

            if (s1 + s2 + s3 + s4 > 0) { $("#star1").text("★"); }

            if (s2 + s3 + s4 > 0) { $("#star2").text("★"); }

            if (s3 + s4 > 0) { $("#star3").text("★"); }

            if (s4 > 0) { $("#star4").text("★"); }

        }

    }



    function fnClick() {

        $("#importance").val($("#star0").text() + $("#star1").text() + $("#star2").text() + $("#star3").text() + $("#star4").text());

    }

});

 

你可能感兴趣的:(JavaScript)