我有相当多的功能,如下所示,都有一些细微的变化,并查询不同的ID。有没有办法连接这个或者我只需要把它们全部写出来?感谢。
function event() {
var path = document.querySelector('#container #path');
var length = path.getTotalLength();
console.log(path.getTotalLength());
path.style.transition = path.style.WebkitTransition =
'none';
path.style.strokeDasharray = length + ' ' + length;
path.style.strokeDashoffset = length;
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition =
'stroke-dashoffset 0.4s linear';
path.style.strokeDashoffset = '0';
document.getElementById("container").style.visibility = "visible";
};
function event2() {
var path2 = document.querySelector('#container2 #path_2');
var length = path2.getTotalLength();
console.log(path2.getTotalLength());
path2.style.transition = path2.style.WebkitTransition =
'none';
path2.style.strokeDasharray = length + ' ' + length;
path2.style.strokeDashoffset = length;
path2.getBoundingClientRect();
path2.style.transition = path2.style.WebkitTransition =
'stroke-dashoffset 0.45s linear';
path2.style.strokeDashoffset = '0';
document.getElementById("container2").style.visibility = "visible";
};
function event3() {
var path3 = document.querySelector('#container3 #path_3');
var length = path3.getTotalLength();
console.log(path3.getTotalLength());
path3.style.transition = path3.style.WebkitTransition =
'none';
path3.style.strokeDasharray = length + ' ' + length;
path3.style.strokeDashoffset = length;
path3.getBoundingClientRect();
path3.style.transition = path3.style.WebkitTransition =
'stroke-dashoffset 0.4s linear';
path3.style.strokeDashoffset = '0';
document.getElementById("container3").style.visibility = "visible";
};
window.setTimeout(function() {
event();
}, 1);
window.setTimeout(function() {
event2();
}, 550);
window.setTimeout(function() {
event3();
}, 1100);
答案 0 :(得分:0)
如果我有一系列几乎相同的功能
function showNumber1() {
window.alert("The number you wish to show is 1");
}
function showNumber2() {
window.alert("The number you wish to show is 2");
window.alert("Okay that's all");
}
function showNumber3() {
window.alert("The number you wish to show is 3");
}
我通常可以用一个函数替换它们,比如
function showNumber(n) {
window.alert("The number you wish to show is " + n);
if (n == 2) {
window.alert("Okay that's all");
}
}
因此,将函数重写为包含保持不变的部分的单个函数,并使用参数和if
语句来表示不同的部分。
此外,您似乎正在使用ID,就好像它们是类一样。而不是
<div id="path_1"> ... <div id="path_2"> ...
您可以使用课程
<div class="path"> ... <div class="path"> ...
并使用document.getElementsByClassName('path')[0]
和document.getElementsByClassName('path')[1]
在您的javascript中识别它们。