当鼠标进入/离开图像时显示隐藏按钮

JQuery - show hide button when mouse enter / leave an image

本文关键字:显示 隐藏 按钮 图像 离开 鼠标      更新时间:2023-09-26

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

$('#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>

使用纯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>

尝试悬停?

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

我没有图像,所以我用div代替。

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

将mouseenter更改为mouseover。

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

try this

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