【问题标题】:Animated Div goes right and left, but not up and down动画 Div 向右和向左移动,但不是向上和向下
【发布时间】:2014-04-06 13:16:50
【问题描述】:

我有一个 div,我正在尝试使用 jQuery 制作动画。我的目标是根据相应的按键向左、上、右和下移动 div。

例如,如果我按左箭头键,则 div 会向左移动等。

目前,当页面加载/刷新时,我的 div 能够向左、向右、向上和向下移动。但是,一旦我将 div 向右移动,我就无法将其向左移动,当我将其向下移动时,我无法将其向上移动,依此类推......

如何让我的 div 在各个方向上更流畅?

jsfiddle:http://jsfiddle.net/6U6cA/4/

我的代码

HTML:

<body>
    <div id="container">
      <div id="switcher">
        <div class="label">TestDiv</div>
        <button id="switcher-default">Default</button>
        <button id="switcher-large">Default 1</button>
        <button id="switcher-small">Default 2</button>
      </div>

    </div>
  </body>

CSS:

#switcher {
  width: 300px;
  padding: .5em;
  border: 1px solid #777;
}
.label {
  width: 130px;
  margin: .5em 0;
  cursor: pointer;
}

jQuery:

$(document).ready(function() {

$('#switcher').css({
  position:'relative',
  display:'inline-block'
});
$(document).keyup(function(event){
  var key=event.which;

  switch(key){
    case 37:
      $('#switcher').animate({right:'+=20'});
      break;
    case 38:
      $('#switcher').animate({bottom:'+=20'});
      break;
    case 39:
      $('#switcher').animate({left:'+=20'});
      break;
    case 40:
      $('#switcher').animate({top:'+=20'});
      break;

  }
});

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    您首先设置left 样式属性,然后设置right,但这不起作用,因为left 未被删除,因此它覆盖了right 样式。

    坚持一个 CSS 属性

    $(document).ready(function () {
    
        $('#switcher').css({
            position: 'relative',
            display: 'inline-block'
        });
        $(document).keyup(function (event) {
            var key = event.which;
    
            switch (key) {
                case 37:
                    $('#switcher').animate({
                        left: '-=20'
                    });
                    break;
                case 38:
                    $('#switcher').animate({
                        top: '-=20'
                    });
                    break;
                case 39:
                    $('#switcher').animate({
                        left: '+=20'
                    });
                    break;
                case 40:
                    $('#switcher').animate({
                        top: '+=20'
                    });
                    break;
    
            }
        });
    
    });
    

    FIDDLE

    【讨论】:

    • 感谢您的快速回复,不过只是一个问题。在我的控制台中,我看到当使用我的代码示例时,div 最终会显示为 left:20px、right:40px、top:40px、bottom 60px。在这种情况下,为什么 left & right、top & bottom 不能相互抵消,让我相当于 right:20px, bottom:20px 而不是 left 属性覆盖 right?
    • 因为不能同时设置左右(设置宽度时),所以必须要赢,在这种情况下是左。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多