鼠标悬停在文本上方时显示图像,根据需要延迟隐藏或立即隐藏(如果鼠标悬停在新文本上)。

3
所以我有一个图像,当鼠标悬停在某个文本上时会显示,当鼠标被移开后它会延迟一段时间才会消失,这很好运作。但是我有多个图像,根据悬停的文本不同可能会显示不同的图像,我想让第一个图像跳过延迟如果其他文本被悬停,这样就不会扩展页面和堆叠图像了。这可行吗?还是我只需要去除延迟?这是用 JQuery 完成的。
$("h2").mouseover(function ()
    {
        let mouseText = $(this).attr("class").split(" ")[0];
        
        switch(mouseText)
        {
            case "wh-light":
                imgID += mouseText;
                break;
            case "wh-hl-ll":
                imgID += mouseText;
                break;
            case "part-hh-ll":
                imgID += mouseText;
                break;
        }

        $(imgID).show();
    });

$("h2").mouseout(function ()
    {
        $(imgID).delay(1000).hide(0);
    });

我可以提供HTML,但我认为它与此并不太相关。非常感谢您的帮助!

1个回答

1
没有您的模板和完整代码,我必须构建一个完整的示例...但以下代码片段应该为您提供了一个很好的示例。您需要跟踪当前图像,并且您的回调函数必须知道延迟启动时当前图像是什么,并将其与当前图像进行比较,以确定是否应该执行任何操作。
因此,我将代码分成了单独的JavaScript函数,并使用setTimeout而不是jquery delay()。实际jquery网站上的文档甚至提到delay函数是有限的,并且没有办法取消自己,因此不应将其视为setTimeout()的替代品。
参考https://api.jquery.com/delay/ 不知道您如何构建imgID变量或清除它...我添加了baseImageID和targetImageID变量,以便您不会仅仅将新字符串连续连接到imgID的末尾...
作为最后的说明...在讲解解决方案时,我喜欢将事物变得非常模块化和冗长,因此请不要对额外的函数产生厌恶...我认为它们使解决方案更易于理解。实际实现可以简化...

let baseImageID = 'image-';
let targetImageID = '';
let currentImageID = '';

const hideImageNow = function(imageID) {
  $(imageID).hide();
  if (currentImageID == imageID) {
    currentImageID = '';
  }
};

const hideImageLater = function(imageID, delay) {
  setTimeout(hideImageNow, delay, imageID);
};

const showImage = function(imageID) {
  if (currentImageID != '') {
    hideImageNow(currentImageID);
  }
  currentImageID = imageID;
  $(imageID).show();
};

$("h2").mouseover(function() {
  targetImageID = baseImageID;
  let mouseText = $(this).attr("class").split(" ")[0];

  switch (mouseText) {
    case "wh-light":
      targetImageID += mouseText;
      break;
    case "wh-hl-ll":
      targetImageID += mouseText;
      break;
    case "part-hh-ll":
      targetImageID += mouseText;
      break;
  }

  showImage(targetImageID);
});

$("h2").mouseout(function() {
  hideImageLater(currentImageID, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接