我正在使用CSS Grid和jQuery进行试验,但遇到了麻烦。我正在尝试按箭头键方向扩展该框,我可以打印console.log,但它不会更新grid-column-start



$(document).ready(function() {
  console.log("ready!");

  $(document).keypress(function(event) {
    console.log(("Key: " + event.which));
  });

  const box = {
    leftSide: $('.boxA').css('grid-column-start'),
    rightSide: $('.boxA').css('grid-column-end'),
    topSide: $('.boxA').css('grid-row-start'),
    bottomSide: $('.boxA').css('grid-row-start'),

    moveLeft: function() {
      if (this.leftSide > 1) {
        console.log(this.leftSide);
        $('.boxA').css('grid-row-start', function() {
          return box.leftSide - 1;
        });
      }
    }
  }

  $(document).keydown(function(e) {
    switch (e.which) {
      case 37:
        box.moveLeft();
        break;

      case 38: // up
        break;

      case 39: // right
        break;

      case 40: // down
        break;

      default:
        return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
  });
});

.mediumboxes {
  width: 100vw;
  height: 100vh;
  background-color: blue;
  display: grid;
  grid-template-columns: repeat(20, 5%);
  grid-template-rows: repeat(10, 10%);
}

.boxA {
  display: block;
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
  background-color: red;
}

.boxB {
  display: block;
  grid-column: 2 / 3;
  grid-row: 1 / 11;
  background-color: orange;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





我想增加leftSide的值而不在第10行再次指定整个DOM路径$('boxA').css('grid-column-start', box.leftSide - 1)

仅引用this.leftside是否可以?

最佳答案

是的只要做this.leftSide = this.leftSide - 1;

您的代码似乎表现为leftSide是一个函数。假设您将其更改为只是一项作业,那么代码本身没有错。

看到这里:http://jsbin.com/pacikas/2/edit?js,console

07-26 02:29