Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*!
* review-star.js v1.0
*
* Copyright (c) 2023 motsu
*
* Released under the MIT license.
* see https://opensource.org/licenses/MIT
*/
class reviewStar{
#els_review_star;
#colors;
constructor(arg_class_name, arg_options){
//色設定
const colors_default = {
base: '#BDBDBD',
star: '#FF8F00'
};
if(arg_options===undefined||arg_options===null||typeof arg_options !== 'object'){
this.#colors = {...colors_default};
}else{
this.#colors = {};
this.#colors.base = arg_options.color_base || colors_default.base;
this.#colors.star = arg_options.color_star || colors_default.star;
}
//対象要素取得
const class_name = arg_class_name || 'review-star';
this.#els_review_star = document.getElementsByClassName(class_name);
//
this.renew();
}
renew(){
[...this.#els_review_star].forEach(element=>{
element.textContent = '';
//パラメータ取得
const size_star = (()=>{
let temp = Number(element.dataset.size) || 16;
if(temp<4) temp = 4;
return temp;
})();
const max_value = (()=>{
let temp = Number(element.dataset.max) || 5;
if(!Number.isInteger(temp)) temp = 5;
if(temp<1) temp = 5;
return temp;
})();
const value = (()=>{
let temp = Number(element.dataset.val) || 0;
if(temp<0) temp = 0;
if(temp>max_value) temp = max_value
return temp;
})();
//必要値計算
const value_grad = (()=>{
if(Number.isInteger(value)) return 0;
return Math.ceil(value);
})();
const rate_star = (value%1) * 100;
//css write
element.style.display = 'inline-flex';
element.style.verticalAlign = 'middle';
//星追加
for(let i=1;i<=max_value;i++){
const el_star = document.createElement('span');
el_star.style.display = 'inline-block';
el_star.style.width = size_star + 'px';
el_star.style.height = size_star + 'px';
el_star.style.clipPath = 'polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%)';
if(i<=value){
el_star.style.backgroundColor = this.#colors.star;
}else if(i>value_grad){
el_star.style.backgroundColor = this.#colors.base;
}else{
el_star.style.background = `linear-gradient(to right, ${this.#colors.star} ${rate_star}%, ${this.#colors.base} ${rate_star}%)`;
}
element.appendChild(el_star);
}
});
}
setColorBase(str){
this.#colors.base = str;
this.renew();
}
setColorStar(str){
this.#colors.star = str;
this.renew();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment