我只需要在 else if block 中设置不同的 animate() 的 marginLeft 值,而 else if block 中的所有其他值应该相同。脚本如下:
var timeoutID = window.setTimeout(
function(){
if (imgs.index(imgElement) == 0) {
imgElement.animate({
width: "315px",
height: "225px",
marginTop: "-50px",
marginLeft: "-150px",
}, 1500 );
imgElement.css("z-index","100");
imgElement.css("position","absolute");
imgElement.css("opacity","1");
}
else if (imgs.index(imgElement) == 1) {
//The same thing but marginLeft: "-200px"
}
}, 1500);
最佳答案
您可以提取变量中的值,根据您的条件设置变量的值,然后使用变量而不是硬编码值。
var marginLeft = "-150px"; // extract the default value in a variable
if (imgs.index(imgElement) == 1) {
marginLeft = "-200px"; // change the value according to conditions
}
imgElement.animate({
width: "315px",
height: "225px",
marginTop: "-50px",
marginLeft: marginLeft, // use the value from the variable
}, 1500);
关于javascript - Jquery-代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6751750/