当用户在输入字段中键入搜索值时,代码将判断该值是否出现在任何列表项中.如果是并且该列表项先前被隐藏,则匹配的列表项闪烁绿色并再次出现;如果不是,则匹配的列表项闪烁红色并消失.
然而,出于某种原因,当它们再次出现时应该闪烁一次绿色的匹配物品似乎闪烁了多次(2次或3次).
您可以在此处进行测试: 只需输入123,然后删除3和2
//jshint esnext:true
document.querySelector('input#search_input').addEventListener('input', search_value);
const logTextarea = document.querySelector('#log');
const list_elements = document.querySelectorAll('ul#list_of_stuff li');
list_elements.forEach(li => {
li.addEventListener('transitionend', transition_ended);
});
function search_value() {
const searchString = document.querySelector('input#search_input').value.toLowerCase();
const list_elements = document.querySelectorAll('ul#list_of_stuff li');
list_elements.forEach(list_element => {
const list_element_value = list_element.textContent.toLowerCase();
if (list_element_value.includes(searchString)) {
if (list_element.className == 'hidden') {
list_element.className = 'flash_green';
}
} else {
if (list_element.className != 'hidden') {
list_element.className = 'flash_red';
}
}
});
}
function transition_ended(event) {
let element = event.target;
logTextarea.value += `Transition ended for ${element.tagName}, at this point className is ${element.className}\n`;
if (element.className == 'flash_red') {
element.className = 'hidden';
}
if (element.className == 'flash_green' || element.className == 'flash_red') {
console.log('Deleting ', element.className);
logTextarea.value += `Deleting ${element.className}\n`;
element.className = '';
}
}
#list_of_stuff li.flash_red {
animation: flash_red 0.5s;
animation-iteration-count: 3;
transition: opacity 0.5s;
opacity: 0;
}
@keyframes flash_red {
0% {
background-color: red;
}
50% {
background-color: transparent;
}
100% {
background-color: red;
}
}
#list_of_stuff li.flash_green {
animation: flash_green 0.5s;
animation-iteration-count: 3;
opacity: 100;
}
@keyframes flash_green {
0% {
background-color: green;
}
50% {
background-color: transparent;
}
100% {
background-color: green;
}
}
.hidden {
display: none !important;
}
<!DOCTYPE html>
<html>
<head>
<title>Input text and list in HTML</title>
</head>
<body>
<input type="text" id="search_input">
<ul id="list_of_stuff">
<li>1</li>
<li>12</li>
<li>123</li>
<li>1234</li>
</ul>
<textarea id="log" style="min-width: 613px; min-height: 500px;"></textarea>
</body>
</html>
同样在这里:https://jsbin.com/yonejoqihu/
这就像,当发生flashgreen时,因为类仍然存在,所以没有触发转换结束.不知道为什么?