点击功能

时间:2017-08-26 05:29:22

标签: javascript jquery html css

我对jQuery很陌生,我很难适应它是一个Java书呆子。

我正在尝试制作这3个盒子,这样当你点击其中一个时,它会向前移动,后面的两个暗淡并留在那里,在后面。问题是,当你连续点击多个框时,我想这样做,点击的第二个框不会直到动画结束,就像一个盒子点击队列。现在它已经混淆了,调光很好,但是一旦我点击它们就会出现盒子,而不是它们应该的时候。

我试过回调并推迟无济于事。

以下是代码:

使用Javascript:

var zindex = 1;

$('.box_listener').click(function() {

  $(this).css('z-index', zindex += 1);
  $(this).siblings('.box_listener').fadeTo(3000, 0.5);
  $(this).fadeTo(1, 1);
});

这是JSFiddle:

https://jsfiddle.net/asger/5yvvgoda/14/



var zindex = 1;

$('.box_listener').click(function() {

  $(this).css('z-index', zindex += 1);
  $(this).siblings('.box_listener').fadeTo(3000, 0.5);
  $(this).fadeTo(1, 1);
});

#backgroundbox {
  position: absolute;
  width: 400px;
  height: 200px;
  background-color: #E5E8E8;
  z-index: -5;
  border-style: solid;
  border-width: 1px;
}

.box_listener {
  position: absolute;
  width: 120px;
  height: 120px;
  background-color: white;
  border-style: solid;
  border-width: 1px;
}

#redbox {
  left: 270px;
  top: 20px;
  border-color: red;
  z-index: 0;
}

#bluebox {
  left: 230px;
  top: 60px;
  border-color: blue;
  z-index: 0;
}

#greenbox {
  left: 210px;
  top: 77px;
  border-color: lightgreen;
  z-index: 0;
}

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

  <div class="box_listener" id="redbox">

  </div>

  <div class="box_listener" id="bluebox">

  </div>

  <div class="box_listener" id="greenbox">

  </div>

</div>
&#13;
&#13;
&#13;

干杯谢谢!

1 个答案:

答案 0 :(得分:0)

更加防弹的方法是根本不使用jQuery动画,而是使用CSS过渡。原因是双重的; CSS转换可以自动反转,并且可以通过GPU加速。这也意味着您不必在允许用户输入之前人为地等待转换完成。

要做到这一点,只需设置两个CSS类;一个告诉您将要动画如何转换的元素。另一个类更改元素上的值,这会导致转换发生。然后,所有jQuery需要做的是addClass()removeClass(),以便进行转换。

下面是它的实例。我已经通过评论强调了最重要的方面。

$('.btn').on('click', function() {
  // remove the active class from all buttons,
  // this will reverse the transition
  $('.btn').removeClass('active');
  // apply it to only the current button clicked,
  //this will start the transition
  $(this).addClass('active');
});
.btn {
  display: block;
  width: 200px;
  padding: 10px 20px;
  margin-bottom: 5px;

  background: cornflowerblue;
  border: 0;
  cursor: pointer;
  
  /* set up a transition on any css transformations like 
     translating, scaling, rotating, etc. */
  transition: transform 300ms ease-in-out;
}

/* when this class is added to the button it will scale it, but the 
   transition already on the button will make sure it happens slowly */
.active {
  transform: scale(1.2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Click the buttons</h2>

<button class="btn">First</button>
<button class="btn">Second</button>
<button class="btn">Third</button>