简体   繁体   English

将Mouseenter和Mouseleave更改为Click

[英]Change Mouseenter and Mouseleave to Click

I have a element which shows up when you hover with a mouse. 我有一个元素,当您将鼠标悬停时会显示出来。 Now we want to change this to click and not mouseenter or -leave. 现在,我们想将其更改为单击,而不是mouseenter或-leave。 What we have: 我们有什么:

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

The HTML HTML

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

The CSS CSS

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

We tried to change it to this, but this doesn't work: 我们尝试将其更改为此,但这不起作用:

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

We just want to slide open on click and slide back out on click again, and not on mouseevent like it is now. 我们只想在单击时滑动打开并在再次单击时滑出,而不是像现在这样在mouseevent上滑动。

One way is to use a boolean to know if it's in the visible position then toggle the boolean, var left=false; 一种方法是使用布尔值来知道它是否处于可见位置,然后切换布尔值, 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> 

An alternate method is to use jquery to get the position and animate it based on position, $(this).position().left 另一种方法是使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM