動的なスターレーティングを実装する方法

WEB制作

こんにちは、やせる子です。

社内サイトに星評価を導入したいといわれ、調べていたのに結局使わないことになったので備忘録として記します。

広告

やりたいこと

数値をかえると、星の色づき方を変えられるようにしたい。

キノコログーCSSのみで星評価レーティングをデザインする方法

デザインや色の付け方は上記記事を参考にさせていただきました。簡単ですごい。

星評価をクリックして色を変える、というページは結構あったんですが評価の値によって色づき方を変えるというページは見つけられなかったので作りました。

もともとはサーバー上に評価を格納して持ってきて、という作り方をしたのですが今回は表面的な部分だけ記したいのでスライダーを使って、値を変えられるようにしました。

スライダー、この存在を知らなくて、でも絶対あると思って頑張って検索して見つけたページも共有しておきます。

CODE KITCHEN ーinput type=”range”でレンジスライダーを作る

できたもの

See the Pen Untitled by ys (@yaseruko) on CodePen.

スライダーを動かすとその値に合うように星の色づきが変化

HTML

    0<input type="range" id="num"  min="0" max="5" step="0.1" onchange="star()">5
    <div id="numval"></div>
    <div class="star star_width" id="starval"></div>

JavaScript

 function star() {
    let num = document.getElementById("num").value;
    let star = document.getElementById("starval");
    let numval = document.getElementById("numval");
    numval.innerHTML = num;

    star.classList.remove(...star.classList);

    if (num == 5) {
        star.classList.add("star_width100");
    } else if (num <= 4.9 && num > 4.4) {
        star.classList.add("star_width90");
    } else if (num <= 4.3 && num > 3.5) {
        star.classList.add("star_width80");
    } else if (num <= 3.5 && num >3) {
        star.classList.add("star_width70");
    } else if (num <= 3 && num > 2.5) {
        star.classList.add("star_width60");
    } else if (num <= 2.5 && num >2) {
        star.classList.add("star_width50");
    } else if (num <= 2 && num > 1.5) {
        star.classList.add("star_width40");
    } else if (num <= 1.5 && num > 1) {
        star.classList.add("star_width30");
    } else if (num <= 1 && num > 0.5) {
        star.classList.add("star_width20");
    } else if (num <= 0.5 && num > 0) {
        star.classList.add("star_width10");
    }else{
        star.classList.add("star_width");
    }

    star.classList.add("star");
    
}

きっともっと短く簡潔に書く方法が必ずあると思う。

CSS

.star {
    position: relative;
    z-index: 0;
    display: inline-block;
    color: darkgray;
}

.star:before,
.star:after {
    content: '★★★★★';
}

.star:after {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    overflow: hidden;
    white-space: nowrap;
    color: gold;
}

.star_width100:after {
    width: 100%
}

.star_width90:after {
    width: 90%
}

.star_width80:after {
    width: 80%
}

.star_width70:after {
    width: 70%
}

.star_width60:after {
    width: 60%
}

.star_width50:after {
    width: 50%
}

.star_width40:after {
    width: 40%
}

.star_width30:after {
    width: 30%
}

.star_width20:after {
    width: 20%
}

.star_width10:after {
    width: 10%
}

.star_width:after {
    width: 0%
}

一応ちゃんと色変わるので満足。


🔽おすすめ本🔽

JS勉強し始めたときに買ったやつ

コメント

タイトルとURLをコピーしました