更改位置后无法将Div重置为居中

时间:2018-12-09 08:36:31

标签: javascript jquery css3

能否请您看一下这个演示,让我知道为什么我无法将.container重新设置为

$("#back").on("click", function(){
      $(".container").animate({
              'margin-left': 'auto',
              'margin-right': 'auto',
              'margin':'0 auto'
        }, 550);
});

$("#move").on("click", function() {
  $(".container").animate({
    'margin-left': '2.1%'
  }, 550);
});

$("#back").on("click", function() {
  $(".container").animate({
    'margin-left': 'auto',
    'margin-right': 'auto',
    'margin': '0 auto'
  }, 550);
});
.container {
  height: 100px;
  background: khaki;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<button type="button" class="btn btn-primary" id="move">Move Left</button>
<button type="button" class="btn btn-secondary" id="back">Get Back</button>
<div class="container"></div>

1 个答案:

答案 0 :(得分:1)

当文档生成Reference to non-existent field 'name'. Error in myscript (line 6) S = load(fullfile(D,S(k).name)); 时,您可以使JavaScript记住margin-left的值!

ready
var margin;

$(document).ready(function() {
  $('.container').css('margin-left', 'auto'); // first, align it in the center
  margin = $('.container').css('margin-left'); // and then, store the value
  // console.log(margin);
});

$("#move").on("click", function() {
  $(".container").animate({
    'margin-left': '2.1%'
  }, 550);
});

$("#back").on("click", function() {
  $(".container").animate({
    'margin-left': margin, // use it anywhere ;)
    'margin-right': 'auto',
    'margin': '0 auto'
  }, 550);
});
.container {
  height: 100px;
  background: khaki;
}