优化此代码JQuery

时间:2017-03-19 18:30:04

标签: javascript jquery

最近我创建了一个旋转对象的代码,代码或多或少地起作用,我已经清理了它,但它看起来仍然很乱,而且它有点儿麻烦。 该代码有效,但是当您打开Chrome控制台并关闭它时代码停止工作,请帮助我!

$(document).ready(restrictHeight);
$(window).resize(restrictHeight);

function restrictHeight() {
  $('.item img').css('max-height',$(window).outerHeight*0.85);
}

1 个答案:

答案 0 :(得分:0)

我不会重构您的所有代码,但请查看一些更改。我无法理解你的代码,因为我无法理解变量和函数名称:D。

很高兴知道阵列开始在zeeerooooo

    $(document).ready(function(){
        var gradiLength = 6;
    var gradi = new Array(gradiLength);
    var scheda = [];
    var schedaLenght = 7;
    var mainDiv = $('main');
    var hero = $('.hero');

    for (var i = 0; i <= schedaLength; i++) {

            //you are using css selectors, please use jquery function children, child, sibblings etc etc.
        scheda.push(mainDiv.find("div:nth-child("+i+")").offset().top));
    }

   // you defined this variable however, you dont even use it
   var schermo = $(window).height();

    $(window).on("scroll", function(){
        var percorso = $(this).scrollTop();
        if (percorso > scheda[0] && percorso < scheda[1]) {
            var quantita = calculateWtf(percorso, scheda, 0)
            ruota(0, quantita);
        } else if (percorso > scheda[1] && percorso < scheda[2]) {
            var quantita = calculateWtf(percorso, scheda, 1)
            ruota(1, quantita);
        } else if (percorso > scheda[2] && percorso < scheda[3]) {
            var quantita = calculateWtf(percorso, scheda, 2)
            ruota(2, quantita);
        } else if (percorso > scheda[3] && percorso < scheda[4]) {
            var quantita = calculateWtf(percorso, scheda, 3)
            ruota(3, quantita);
        } else if (percorso > scheda[4] && percorso < scheda[5]) {
            var quantita = calculateWtf(percorso, scheda, 4)
            ruota(4, quantita);
        } else {
            hero.css({ transform: "rotateX(0deg)"});
        }
    });

    function calculateWtf(p, s, index) {
      var DIVIDER = 10;
        return (p-s[index])/DIVIDER;
    }

    //wth is ruota? and what is i and n? Please use english words with a better naming
    function ruota(i, n){
        var indice = i-1;
        var opacita = n/110;
        gradi[indice] = n;

        // however I would look into child parent sibling jquery functions
        mainDiv.find("div:eq("+indice+") > div")
            .css({ transform: "rotateX("+gradi[indice]+"deg)", opacity: 1-opacita });

        mainDiv.find("div:eq("+indice+") > div")
            .css("transform", "rotateX(0deg)");
    }
});





请用英文编写您的代码,因为如果您再次在stackoverflow上发帖,那么没有人会理解您的代码真正做了什么