javascript 基于平均值的星星评定- Vanilla JS

qacovj5a  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(108)

我似乎找不到解决办法。
我只需要根据固定的平均数来显示星星。所以半颗星代表0.5以上的小数,而星代表整数,轮廓星代表0.5以下的值。
根据数据

const shirt = {
  name: "White Shirt",
  newPrice: 10.99,
  oldPrice: 29.99,
  avgRating: 4.3
}
const productDetail = document.querySelector('.product-detail')
productDetail.innerHTML = `
<h2>${shirt.name}</h2>
<div class="sale-perc">
  <span>33% OFF</span>
</div>
<div class="price-review">
  <div class="price">
    <span class="new-price">${shirt.newPrice}</span>
    <span class="old-price">${shirt.oldPrice}</span>
  </div>
  <div class="review-rating">
   <div class="review-stars">
   <p>
   ${(() => {
     let rating = ''
     const avgRating = shirt.avgRating

     for (let i = 0; i < 5; i++) {
       if (i < avgRating) {
         rating += `<i class="fa-solid fa-star"></i>`
       } else if (i === avgRating && avgRating % 1 !== 0) {
         rating += `<i class="fa-solid fa-star-half-alt"></i>`
       } else {
         rating += `<i class="fa-regular fa-star"></i>`
       }
     }
     return rating
   })()}
    </p>
   </div> 
</div>
</div>
lo8azlld

lo8azlld1#

let rating = ''
const avgRating = shirt.avgRating

for (let i = 1; i <= avgRating; i += 0.5) {
  if (i % 1 === 0) {
      rating += `<i class="fa-solid fa-star"></i>`;
  } else if (i % 1 !== 0 && i === avgRating) {
    rating += `<i class="fa-solid fa-star-half-alt"></i>`;
  }
}

return rating;

相关问题