喝水
html部分
<h1>Goal: 2 Liters</h1>
<div class="cup cupbig"><div class="remained"><span id="liters">2L</span><small>Remained</small></div><div class="percentage">1%</div>
</div>
<p class="text">Select how many glasses of water that you have drank</p><div class="cups"><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div><div class="cup cupsmall">250ml</div>
</div>
css部分
*{margin: 0;padding: 0;
}
:root{--border-color:#144fc6;--fill-color:#6ab3f8
}body{background-color: #3494e4;color: white;display: flex;flex-direction: column;align-items: center;justify-content: center;min-height: 100vh;
}
h1{margin: 10px 0 0;
}
h3{font-weight: 400;margin: 10px 0;
}
.cup{background-color: #fff;border: 4px solid var(--border-color);color: var(--border-color);display: flex;flex-direction: column;align-items: center;justify-content: center;margin: 10px 0;overflow: hidden;
}
.remained{display: flex;justify-content: center;align-items: center;flex-direction: column;text-align: center;overflow: hidden;flex: 1;transition: 0.3s;
}
.remained span{font-size: 20px;font-weight: bold;
}
.remained small{font-size: 12px;
}
.percentage{background-color: var(--fill-color);display: flex;justify-content: center;align-items: center; font-weight: bold;font-size: 30px;transition: 0.3s; width: 100%;height: 0;overflow: hidden;border-radius: 0 0 34px 34px;
}
.cupbig{height: 330px;width: 150px;border-radius: 0 0 40px 40px;
}
.cupsmall{height: 95px;width: 50px;border-radius: 0 0 40px 40px;cursor: pointer;
}
.full{background-color: var(--fill-color);
}
.text{margin: 30px 0;
}.cups{display: grid;grid-template-columns: repeat(4,1fr);gap: 10px;
}
js部分
// 获取dom
const cupsmalls=document.querySelectorAll('.cupsmall');
const cupbig=document.querySelector('.cupbig');
const liters=document.querySelector('#liters');cupsmalls.forEach(((item,index)=>{// 给点击盒子增加点击事件item.addEventListener('click',()=>hightlightCups(index))
}))// 高亮小杯子
function hightlightCups(p_index){if(p_index===7&cupsmalls[p_index].classList.contains('full')){p_index--;}else if(cupsmalls[p_index].classList.contains('full')&&!cupsmalls[p_index].nextElementSibling.classList.contains("full")){p_index--;}// 点击元素前面填充或者移除cupsmalls.forEach((item,c_index)=>{if(c_index<=p_index){item.classList.add('full');}else{item.classList.remove('full');}})full_big()}// 填充大杯子
function full_big(){const fulls_len=document.querySelectorAll(".full").length;const cup_box=cupbig.getBoundingClientRect();if(fulls_len==cupsmalls.length){cupbig.children[0].style.height=0}// 计算显示文本liters.innerHTML=`${2-((fulls_len*2)/cupsmalls.length)}L`cupbig.children[1].style.height=`${fulls_len/cupsmalls.length*cup_box.height}px`;cupbig.children[1].innerHTML=`${fulls_len/cupsmalls.length*100}%`
}
效果