function createFlake(){
var el= document.createElement('i');
el.classList.add("fab");
el.classList.add("fa-bitcoin")
el.classList.add("fa-7x")
el.style.left=Math.random()* window.innerWidth+'px';
el.style.animationDuration= Math.random()*3+ 3 +'s';
el.style.opacity=Math.random();
let score=5;
el.addEventListener('mouseover',()=>{
score=score+1;
console.log(score)
el.classList.add('fa-bitcoin-hover');
var s=document.getElementById('scor');
s.innerText="Score: "+score;
})
document.body.appendChild(el)
}
使用上面的代码,我正在创建从上到下下降的图标,并且这样做,每次我将鼠标悬停在图标上时,我都希望它增加得分。一切正常,除非我保持相同的分数或+1。不能增加分数。
答案 0 :(得分:1)
将let score
移动到函数外部,除非您需要每个薄片都具有自己的分数
let score = 5;
const s = document.getElementById('scor');
function createFlake() {
var el = document.createElement('i');
el.classList.add("fab");
el.classList.add("fa-bitcoin")
el.classList.add("fa-7x")
el.style.left = Math.random() * window.innerWidth + 'px';
el.style.animationDuration = Math.random() * 3 + 3 + 's';
el.style.opacity = (Math.random()+0.009).toFixed(2); // or you get invisible flakes
el.addEventListener('mouseover', () => {
score++
el.classList.add('fa-bitcoin-hover');
s.innerText = "Score: " + score;
})
document.body.appendChild(el)
}
createFlake()
createFlake()
createFlake()
createFlake()
.fa-bitcoin-hover { border: 1px solid black; }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
<span id="scor">Score: 5</span>
<hr/>
如果每次击中薄片都获得积分,即使击中同一薄片不止一次,您也需要这样:
const s = document.getElementById('scor');
const showScore = () => {
let total = 0;
[...document.querySelectorAll(".fab")].forEach(el => total += +el.title)
s.innerHTML = total;
}
function createFlake() {
var el = document.createElement('i');
el.classList.add("fab");
el.classList.add("fa-bitcoin")
el.classList.add("fa-7x")
el.style.left = Math.random() * window.innerWidth + 'px';
el.style.animationDuration = Math.random() * 3 + 3 + 's';
el.style.opacity = (Math.random()+0.009).toFixed(2); // or you get invisible flakes
let score = 5;
el.addEventListener('mouseover', () => {
score++
el.classList.add('fa-bitcoin-hover');
el.title = score;
showScore();
})
document.body.appendChild(el)
}
createFlake()
createFlake()
createFlake()
createFlake()
.fa-bitcoin-hover { border: 1px solid black; }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
<div>Score: <span id="scor">5</span>
<hr/>
答案 1 :(得分:0)
您可以添加分数作为元素的属性,而不是获取可变分数。只需el.score
,请参见下面的代码:
el.score = 5;
el.addEventListener('mouseover', ()=> {
el.score++;
console.log(el.score);
el.classList.add('fa-bitcoin-hover');
let s = document.getElementById('score');
s.innerText = "Score: " + el.score;
});