我正在try 使用js和jQuery为我的Django项目制作一个星级评级系统. 当鼠标放在每颗星星上时,我想改变星星的 colored颜色 .
我不想让星星的 colored颜色 停留在悬停状态.
I followed this tutorial on YouTube.
In this video it seems to work.
JavaScript method preferred
(function($) {
"use strict";
$(document).ready(function() {
const starone = document.getElementById('star-first')
const startwo = document.getElementById('star-second')
const starthird = document.getElementById('star-third')
const starfourth = document.getElementById('star-fourth')
const starfifth = document.getElementById('star-fifth')
const form = document.querySelector('.rate-form')
const confirmBox = document.getElementById('confirm-score')
const csrf = document.getElementsByName('csrfmiddlewaretoken')
const handleStarSelect = (size) => {
const children = form.children
for (let i = 0; i < children.length; i++) {
if (i <= size) {
children[i].classList.add('checked')
} else {
children[i].classList.remove('checked')
}
}
}
// handleStarSelect(2)
const handleSelect = (selection) => {
switch (selection) {
case 'star-first':
{
// starone.classList.add('checked')
// startwo.classList.remove('checked')
// starthird.classList.remove('checked')
// starfourth.classList.remove('checked')
// starfifth.classList.remove('checked')
handleStarSelect(1)
return
}
case 'star-second':
{
handleStarSelect(2)
return
}
case 'star-third':
{
handleStarSelect(3)
return
}
case 'star-fourth':
{
handleStarSelect(4)
return
}
case 'star-fifth':
{
handleStarSelect(5)
return
}
}
}
const arr = [starone, startwo, starthird, starfourth, starfifth]
arr.forEach(item => item.addEventListener('mouseover', (event) => {
handleSelect(event.target.id)
}))
});
})(jQuery);
.checked {
color: #f2994a;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<div class="user-rating">
<form action="" method="post" class="rate-form">
{% csrf_token %}
<button type="submit" class="fa fa-star fa-lg" id="star-first"></button>
<button type="submit" class="fa fa-star fa-lg" id="star-second"></button>
<button type="submit" class="fa fa-star fa-lg" id="star-third"></button>
<button type="submit" class="fa fa-star fa-lg" id="star-fourth"></button>
<button type="submit" class="fa fa-star fa-lg" id="star-fifth"></button>
</form>
<div id="confirm-score"></div>
</div>