我制作了這個腳本,讓我可以在懸停特定字母時更改字母。
我希望能夠懸停一個字母,將其更改為A,一旦mouseleave事件被呼叫,該字母就會變回原來的字母。
const toLetterize = document.querySelectorAll(
".change p"
);
console.log(toLetterize);
toLetterize.forEach(function (letterized) {
const letters = letterized.innerHTML;
var nHTML = "";
for (var letter of letters) {
nHTML = "<u>" letter "</u>";
}
letterized.innerHTML = nHTML;
document.querySelectorAll("u").forEach(function (hoveredLetter) {
hoveredLetter.addEventListener("mouseenter", function (e) {
console.log("hovered")
hoveredLetter.innerHTML = nextLetter(hoveredLetter.innerText);
});
hoveredLetter.addEventListener("mouseleave", function (e) {
console.log("leaving" nextLetter(hoveredLetter.innerText))
hoveredLetter.innerHTML = nextLetter(hoveredLetter.innerText);
});
});
});
function nextLetter(ch) {
console.log(ch);
if (!ch.match(/[a-z]/i)) {
return "A";
} else if (ch === "A") {
return ch;
}
return String.fromCharCode(ch);
}
div{
font-family: monospace;
}
<div class="change">
<p> The colours of the binding (chosen by me) will be white letters on a blue field – the Greek flag though really of Bavarian origin and imported with the dynasty. Yet in a special way they symbolise the myth well – the white islands scattered over the sea.</p>
</div>
uj5u.com熱心網友回復:
您的事件處理程式應該從引數(e.target或e.currentTarget)中的事件物件中獲取觸發事件的元素。
另外,您應該跟蹤原始信件。data-original在制作u包含每個字母的元素時,我將它放在資料屬性 ( ) 中。
因此,mouseenter現在的事件處理程式只是更改innerText懸停元素的 ,A而事件處理程式mouseleave只是更改innerText元素的 失去游標與開頭的原始字母。
const toLetterize = document.querySelectorAll(".change p");
toLetterize.forEach(function(letterized) {
const letters = letterized.innerHTML;
let nHTML = "";
for (let letter of letters) {
nHTML = `<u data-original='${letter}'>${letter}</u>`;
}
letterized.innerHTML = nHTML;
document.querySelectorAll("u").forEach(function(letter) {
letter.addEventListener("mouseenter", function(e) {
const hoveredElement = e.currentTarget;
const currentLetter = hoveredElement.innerText;
hoveredElement.innerText = 'A';
});
letter.addEventListener("mouseleave", function(e) {
const hoveredElement = e.currentTarget;
const originalLetter = hoveredElement.dataset['original'];
hoveredElement.innerText = originalLetter;
});
});
});
div {
font-family: monospace;
}
u{
cursor: pointer;
}
<div class="change">
<p>The colours of the binding (chosen by me) will be white letters on a blue field – the Greek flag though really of Bavarian origin and imported with the dynasty. Yet in a special way they symbolise the myth well – the white islands scattered over the sea.</p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534628.html
上一篇:如何遍歷陣列陣列以查找重復項
