将 Mouseenter 和 Mouseleave 更改为单击

Change Mouseenter and Mouseleave to Click

我有一个元素,当您用鼠标悬停时会显示该元素。现在我们想将其更改为单击而不是鼠标输入或 - 离开。我们有什么:

$('#element').mouseenter(function(){
$(this).stop().animate({'left': '0px'}, 500);
}).mouseleave(function(){
$(this).stop().animate({'left': -($('#element').width()-10)}, 500);
});

HTML

<div class="element" id="element"> </div>

CSS

.element {
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    z-index: 1000;
}

我们试图将其更改为此,但这不起作用:

$('#element').click(function(){
$(this).stop().animate({'left': '0px'}, 500);
}).mouseleave(function(){
$(this).stop().click({'left': -($('#element').width()-10)}, 500);
});

我们只想在点击时滑动打开并在再次点击时滑出,而不是像现在这样在鼠标事件上滑动。

一种方法是使用布尔值来了解它是否处于可见位置,然后切换布尔值,var left=false;

var left = false;
$('#element').click(function() {
  if (left) {
    $(this).stop().animate({
      'left': '0px'
    }, 500);
    left=false;
  } else {
    $(this).stop().animate({
      'left': -($('#element').width() - 10)
    }, 500);
    left=true;
  }
});
.element {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 100%;
  z-index: 1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" id="element">Element</div>

另一种方法是使用 jquery 获取位置并根据位置设置动画,$(this).position().left

$('#element').click(function() {
  if ($(this).position().left!=0) {
    $(this).stop().animate({
      'left': '0px'
    }, 500);
  } else {
    $(this).stop().animate({
      'left': -($('#element').width() - 10)
    }, 500);
  }
});
.element {
  position: fixed;
  top: 0px;
  left: 0px;
  height: 100%;
  z-index: 1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" id="element">Element</div>