首先识别鼠标点击,如果没有触发鼠标悬停

时间:2016-12-13 10:40:52

标签: javascript jquery mouseover mouseclick-event

我有两个功能:mouseovermouseclick。我在相应的事件中写了相应的功能。但问题是,即使我打算mouseover,每次都会触发mouseclick

有没有办法首先识别mouseclick,如果没有,则触发mouseover事件?

$('.test').mouseover(function (event) {
    // ...
}

$('.test').mouseclick(function (event) {
    // ...
}

3 个答案:

答案 0 :(得分:0)

如果没有鼠标悬停,您无法点击。如果是链接或按钮,您可以使用"标签"密钥并到达那里并点击它,但一般使用鼠标它是不可能的。

答案 1 :(得分:0)

您没有使用正确的方法来做这件事,但您仍然可以使用解决方案来实现您的要求。

var myVar;
$('.test').mouseenter(function (event) {
     myVar = setTimeout(function(){ 
       console.info('over')
     }, 2000);         
})

$('.test').click(function (event) {
     clearTimeout(myVar);    
    console.info('click')
})

在此代码中,当您将鼠标悬停在元素上时,它会将代码设置为在2秒后运行。但是如果在2秒之前单击该元素,它将清除超时并且不会在settimeout函数中运行代码。在这种情况下,最好使用 mouseenter 代替 mouseover 。 祝你好运:))

答案 2 :(得分:0)

但是,您可以先使用标记触发click事件。 尝试运行下面给出的代码段,然后点击灰色区域:

$clicked = false;

$('.test').on("click", function (event) {
    $('.msg').append("<div>click</div>").delay(3000).find("div:last").fadeOut(200, function(){$(this).remove();});
    $clicked = !$clicked;
    if($clicked)
      $(this).mouseover();
});

$('.test').on("mouseover", function (event) {
    if($clicked){
        $('.msg').append("<div>mouseover</div>").delay(10000).find("div:last").fadeOut(500, function(){$(this).remove();});
    }
    else $(this).html('');
});

$('.test').on("mousemove", function (event) {
    if($clicked){
        $(this).html("mousemove: pageX: " + event.pageX + ", pageY: " + event.pageY);
    }
    else $(this).html('');
});
.test {
  min-height: 100px;
  border: 1px solid gray;
  background-color: #efefef;
  }
.msg {
  max-height: 100px;
  overflow: auto;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
  
</div>
<div class="msg"></div>