javascript - Jquery-代码优化

标签 javascript jquery coding-style

我只需要在 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/

相关文章:

c++ - 在单个 header 中定义全局(外部)变量更好,还是在各自的头文件中定义更好?

javascript - JavaScript 中 getElementById 方法返回 null

JavaScript 不适用于计算器

php - jQuery "load()"无法加载 PHP "curl_exec()"结果

javascript - 闭包之间垃圾收集的困惑

javascript - 如何用highchart制作讲台

javascript - 如何在应用程序中添加jquery循环插件效果

haskell - 何时在 Haskell 中利用类型推断?

coding-style - 您见过的最无用的评论是什么?

javascript - 快速解决 DOM 中 JQuery .remove() 前导空白的方法?