【问题标题】:jquery .mouseover() mouseout() item appearsjquery .mouseover() mouseout() 项目出现
【发布时间】:2015-04-05 04:24:47
【问题描述】:

我试图让该项目在鼠标悬停时隐藏自己,不幸的是,如果鼠标在该项目上停留一段时间,它会一直显示。

知道我做错了什么吗?

当鼠标悬停在项目上时,我需要它保持隐藏状态,并且仅在鼠标离开时出现。

$('#test').mouseover(function() {
  $('#test').hide();
});

$('#test').mouseout(function() {
  $('#test').fadeIn(500);
});
#test {
  width: 100px;
  height: 100px;
  background: blue;
  position: absolute;
  top: 10px;
  left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="test"></div>

jsfiddle demo

【问题讨论】:

  • 很高兴您使用 jsfiddle 添加了一个最小的测试用例。但是您也应该始终在问题本身中包含相关代码。这里的问题和答案不应依赖于外部来源。

标签: jquery mouseover mouseout


【解决方案1】:

你的代码发生了什么很有趣,据我所知它应该可以工作。你试过只使用 CSS 吗?

    #test {
    width:100px;
    height:100px;
    background-color: blue;
    position: absolute;
    top: 10px;
    left: 10px;
    /* HOVER OFF */
    -webkit-transition: background-color 2s;
}
#test:hover {
    background-color: transparent;
    /* HOVER ON */
    -webkit-transition: background-color 2s;
}

您可以更改转换的时间。并且不要忘记禁用问题中包含的 jQuery 代码。与我对背景的处理方式相同,您可以使用“显示”。我希望这会有所帮助。

Fiddle

【讨论】:

    【解决方案2】:

    使用容器 div 来解决这个问题。原因:当div消失时触发mouseout事件。

    $('#container').mouseenter( function(){
    		
           $('#test').fadeOut();
        console.log("enter");
    	});
    $('#container').mouseleave( function (){
            $('#test').fadeIn();
        console.log("leave");
    });
    #test {
    	    width:100px;
    	    height:100px;
    	    background: blue;
    	    
    	}
    
    #container{
           width:100px;
    	    height:100px;
        position: absolute;
    	    top: 10px;
    	    left: 10px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="container">
    <div id="test"></div>
    </div>

    【讨论】:

      【解决方案3】:

      原因是隐藏元素会触发它的鼠标离开功能,因为它会在消失时离开元素本身。

      您可以添加一个包装元素,例如,

      <div id="demo">
          <div id="test"></div>
      </div>
      

      并在其上附加事件处理程序。

      代码:

      $('#demo').mouseover(function () {
          $('#test').hide();
      });
      $('#demo').mouseout(function () {
          $('#test').fadeIn(500);
      });
      

      演示:http://jsfiddle.net/04wL1rb9/15/

      【讨论】:

        猜你喜欢
        • 2011-03-03
        • 1970-01-01
        • 2016-02-20
        • 2013-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-09
        相关资源
        最近更新 更多