点击后2个div之间的替代z-index?

时间:2015-04-22 15:20:00

标签: javascript jquery html

我对JS不太好所以一直在尝试使用试错法来弄清楚如何通过点击触发器(按钮)获得2个div来交换z-index。

我目前有2个抽屉,技术上相互叠加,从右侧滑出。单击“购买”时,#QuickShopDrawer应该打开,单击“购物车”或“添加到购物车”时,应打开#CartDrawer。

链接到我的test store

到目前为止,我的代码正在使用#CartDrawer打开,使用更高的z-index。

JS:

Drawer.prototype.init = function () {
$(this.config.open).on('click', $.proxy(this.open, this));

$('.js-drawer-open-right-two').click(function(){
  $(this).data('clicked', true);
});

if($('.js-drawer-open-right-two').data('clicked')) {
  //clicked element, do-some-stuff
  $('#QuickShopDrawer').css('z-index', '999');
} else {
  //run function 2
  $('#CartDrawer').css('z-index', '999');
}

this.$drawer.find(this.config.close).on('click', $.proxy(this.close, this));
};

我已经尝试了这个更多我想要的东西,但它只发射一次?

$('.js-drawer-open-right-two').click(function() {
  var i = $(this).index();
  $('.drawer--right').hide();
  $('.drawer--right-two' + (i+1)).show();
});

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您需要在按钮点击时交换元素的z-index。此外,您可以点击disable按钮,以便用户无法连续点击它。

Demo



$(document).ready(function() {
  $('#buy').on('click', function(e) {
    var myZindex = $('#QuickShopDrawer').css('z-index');
    $('#QuickShopDrawer').css('z-index', $('#CartDrawer').css('z-index'));
    $('#CartDrawer').css('z-index', myZindex);
    $(this).prop('disabled', true).siblings('button').prop('disabled', false);
  });

  $('#addToCart').on('click', function(e) {
    var myZindex = $('#CartDrawer').css('z-index');
    $('#CartDrawer').css('z-index', $('#QuickShopDrawer').css('z-index'));
    $('#QuickShopDrawer').css('z-index', myZindex);
    $(this).prop('disabled', true).siblings('button').prop('disabled', false);
  });

});

button {
  position: absolute;
  top: 150px;
  left: 0;
  clear: both;
}
#addToCart {
  margin-left: 50px;
}
.red {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: red;
  left: 20px;
  top: 20px;
  z-index: 1;
}
.green {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: green;
  z-index: 2;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div>
  <div id="QuickShopDrawer" class="red">fdsafdsafdsa</div>
  <div id="CartDrawer" class="green">fdsafdsafdsa</div>
</div>
<button id="buy">Buy</button>
<button id="addToCart">Add To Cart</button>
&#13;
&#13;
&#13;