【问题标题】:JQuery - show hide button when mouse enter / leave an imageJQuery - 当鼠标进入/离开图像时显示隐藏按钮
【发布时间】:2015-09-05 01:55:36
【问题描述】:

在我的网页中,我有一张图片,上面有一个按钮。我想在鼠标进入和离开图像时显示和隐藏按钮:

$('#UserImage').mouseenter(function()
    {
        $('#ButtonChange').show();
    }).mouseout(function()
    {
        $('#ButtonChange').hide();
    })

它正在工作,但是当鼠标进入按钮时,按钮包含在图像中,因此它被认为是离开图像,因此按钮被隐藏,然后在按钮被隐藏的同时,mouseenter 事件被再次触发,并且显示按钮会导致闪烁效果

有解决这个问题的建议吗?

编辑:

$('#UserImage').mouseenter(function() {
  $('#ButtonChange').show();
}).mouseout(function() {
  $('#ButtonChange').hide();
})
.imageUser {
  width: 150px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="position:relative;width=150px">
  <img ID="UserImage" class="imageUser" ImageUrl="~/Images/logo.jpg" />
  <input type="button" ID="ButtonChange" Text="Change" style="position: absolute;top: 180px;height:25px;left:0px;width:100px;display:none">
</div>

【问题讨论】:

  • 请做一个小提琴
  • 添加了代码sn-p

标签: javascript jquery html


【解决方案1】:

使用纯 CSS 也可以实现一切!对于这么简单的事情,你真的不需要 Jquery !

.imageUser {
  width: 150px;
  height: 200px;
}
.img-wrapper {
  position: relative;
  width: 150px
}
.img-btn {
  position: absolute;
  top: 180px;
  height: 25px;
  left: 0px;
  right:0; /* gave right, to align the button in center */
  margin:0 auto; /* as button as fixed width, margin aligns in center */
  width: 100px;
  display: none
}
.img-wrapper:hover .img-btn {display:block} /* whenever mouse hovers the image wrapper, the button is shown, other time, its hidden */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="img-wrapper">
  <img ID="UserImage" class="imageUser" ImageUrl="~/Images/logo.jpg" />
  <input type="button" ID="ButtonChange" Text="Change" class="img-btn">
</div>

【讨论】:

    【解决方案2】:

    试试悬停?

    $("#UserImage").hover(function () {
        $('#ButtonChange').show();
    }, function () {
        $('#ButtonChange').hide();
    });
    

    我没有图像,所以我创建了一个 div。请参阅下面的小提琴。

    小提琴:https://jsfiddle.net/9koswww1/1

    【讨论】:

      【解决方案3】:

      将 mouseenter 更改为 mouseover。

      https://api.jquery.com/mouseenter/ 查看页面底部的示例。

      【讨论】:

      • 请将此类答案作为评论发布。这不是答案!
      【解决方案4】:

      试试这个

      $('#UserImage').mouseenter(function()
      {
          $('#ButtonChange').show();
      }).mouseleave(function()
      {
          $('#ButtonChange').hide();
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-19
        • 1970-01-01
        • 2014-01-10
        • 2013-01-02
        • 2011-02-09
        • 2019-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多