Jquery的悬停和相关功能不起作用

问题描述 投票:1回答:1

我的开发团队已经困扰了一段时间。我们正在尝试通过将鼠标悬停在.tg-item元素上来进行更改,并将图像从“ -prime.png”更改为“ -hover.png”。我知道.replace()是一种骇人听闻的方式,我们只是试图使鼠标位置检测正常工作。我已经附加了到目前为止我们尝试过的所有方法:

$(function(){
  $('.tg-item').on('mouseenter',function(){
    this.innerHTML = this.innerHTML.replace("-prime","-hover");
  }).on("mouseleave",function(){
    this.innerHTML = this.innerHTML.replace("-hover","-prime");
  })
});
///////////////////////////////////////////////////////
$(function(){
  $('.tg-item').hover(
    function(){
      this.innerHTML = this.innerHTML.replace("-prime","-hover")
    },function(){
      this.innerHTML = this.innerHTML.replace("-hover","-prime");
    }
  );
});
///////////////////////////////////////////////////////
$(function(){
  $(document).on("mouseenter", ".tg-item", function(event){
    this.innerHTML = this.innerHTML.replace("-prime","-hover");
  });
  $(document).on("mouseleave", ".tg-item", function(event){
    this.innerHTML = this.innerHTML.replace("-hover","-prime");
  });
});
///////////////////////////////////////////////////////
$(function(){
  var a=$('.tg-item');
  for(var i in a){
    a[i].onmouseover=function(){this.innerHTML = this.innerHTML.replace("-prime","-hover");};
    a[i].onmouseout=function(){this.innerHTML = this.innerHTML.replace("-hover","-prime");};
  }
});

鼠标悬停(使图像变为“-悬停”状态一直有效,第一次更改了图像。但是事情是鼠标关闭事件根本不会可靠地触发。在某些罕见的情况下,我们会随机移动鼠标,这会触发鼠标关闭事件。

关于如何解决悬停/ mouseleave事件功能的任何建议,将不胜感激

jquery html events mouseevent dom-events
1个回答
0
投票

替换html是一个不好的解决方案,找到图像并替换src。

$(function(){
  $('.tg-item').on('mouseenter mouseleave',function(e){
    var isHovered = e.type === "mouseenter"
    var match = isHovered ? "200/300" : "400/400"
    var replacement = !isHovered ? "200/300" : "400/400"
    $(this)
      .find("img")
        .attr("src", function(ind, val) {        
          return val.replace(match, replacement); 
        })
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tg-item">
  <img src="http://placekitten.com/200/300" style="width:200px; height:200px"/>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.