function flash(color){
var count = 0;
var interval = setInterval(function() {
if (++count === 7) {
window.clearInterval(interval);
}
else {
if (count % 2 == 0) {
$('#row').css({'background-color':'white'})
}
else {
$('#row').css({'background-color':color})
}
}
}, 1000);
}它应该闪烁3次(1秒开,1秒关)。有没有更简洁的方法?另外,“白色”只是表示没有颜色,所以最好不要使用颜色。谢谢。
发布于 2018-07-25 22:57:25
我爱我的一些ES6。
const flash = color => {
let count = 0;
const interval = setInterval(() => {
if (++count === 7) clearInterval(interval);
else $('#row').css('background-color', count % 2 ? color : 'white');
}, 1000);
}发布于 2018-07-25 23:36:05
“整洁”和“简明”在某种程度上是主观的术语,我与其他答案不同,将它们等同于“最少的行”。
在这种情况下,我建议根据DRY原则确定要进行哪些更改:不要重复自己。创建DRY代码的方法被称为“语义压缩”,我们可以在这里应用它。
首先,查找您的代码中正在重用的部分。只有一个部分,也就是jquery代码行的开头:$('#row').css({'background-color':。这标识了我们可以清理的代码部分。有一种简单的方法可以避免重复这句话:
function flash(color){
var count = 0;
var interval = setInterval(function() {
if (++count === 7) {
window.clearInterval(interval);
}
else {
var new_color = color;
if (count % 2 == 0) {
new_color = 'white';
}
$('#row').css({'background-color':new_color});
}
}, 1000);
}在这里,您将这两行jquery压缩为一行,并将其中一行作为对color的赋值,这是您的代码中唯一的一行。再次扫描重复的部件时,您可以看到没有一项操作超过一次。然后,您可以去掉大括号,使用ES6语法,使用三元组将条件语句塞到一行中,或者任何类型的偏好,但这取决于解释是否更简洁。在我看来,这只会降低可读性,你可以看到你是否在重复自己,如果不是,你就是在一段干净而简洁的代码中。
发布于 2018-07-25 23:46:58
改为使用CSS animations,这样您的实际动画逻辑将与样式代码( CSS)分离,并且应用动画的逻辑也将模块化到它自己的位置:
function animationEndCallback(e) {
e.target.classList.remove(e.animationName);
e.target.removeEventListener("animationend", animationEndCallback);
}
function cleanAnimation(el, animation) {
el.addEventListener("animationend", animationEndCallback);
el.classList.add(animation);
}
const toBeFlashed = document.getElementById("el");
const btn = document.getElementById("flasher");
btn.addEventListener("click", () => {
cleanAnimation(toBeFlashed, "flashy");
});@keyframes flashy {
from {
background-color: transparent;
}
to {
background-color: rgb(116, 195, 224);
}
}
.flashy {
animation: 1s flashy 4 alternate;
}<div id="el">Hello</div>
<button id="flasher" type="button">Flash</button>
https://stackoverflow.com/questions/51521978
复制相似问题