动态鼠标输入

Dynamic mouseenter

我附加了一些带有内部 img 标签的 div。每个标签都有自己唯一的 id = "theImg"+i 其中 "i" 是数字。我想将鼠标悬停在特定的 img 上并显示 span 的内容(它也有特定的 id 和数字)。到目前为止,这是我的代码,但无法正常工作。

var j;  
document.onmouseover = function(r) {
    console.log(r.target.id);
    j = r.target.id;
}

$(document).on({
    mouseover: function(e){
     $("span").show();
    },
    mouseleave: function(e){
     $("span").hide();
    }
}, "img#"+j);

所以问题是您试图在动态选择器 ("img#"+j) 上设置您的处理程序,但这不起作用。一方面,当 j 未定义时,该等式只会在页面加载时计算一次。

所以您想这样做:

  1. 仅针对鼠标悬停的 img 标签...更好的是,为您的特殊图像提供完全相同的 css class 这样您就可以仅将事件处理程序附加到那些。这样会更有效率。
  2. 当鼠标悬停在图像上或移出图像时,获取它的 id 属性,从中提取数字,然后使用它为要显示的适当范围构建选择器。

    var get_span_from_image = 函数(图像){ var image_id = image.attr("id"); var matches = image_id.match(/theImg(\d+)/); 如果(匹配)return $("theSpan" + 匹配[1]); return $(); // 没有找到,return 一个空的 jQuery 选择 }; $("img").悬停( function() { // 鼠标悬停 get_span_from_image($(this)).show(); }, function() { // 鼠标移开 get_span_from_image($(this)).hide(); } );

注意:有更好的方法将两个节点 "link" 在一起,但这只是用您当前的结构回答您的问题。

更新:link 两个节点在一起的一些想法

因此,与其尝试从 id 属性中提取数字,更好的方法是告诉其中一个图像或 span 关于它的兄弟。您可以像这样输出 html,例如:

<img id="theImg1" data-target="theSpan1" class="hoverable" src="..."/>
....
<span id="theSpan1">...</span>

当然现在您的想法可以是任何东西 - 您不必使用数字值或任何东西。

那么你的悬停代码就变得很简单了:

var get_span_from_image = function(image) {
    var span_id = image.data("target");
    return $("#" + span_id);
};
$("img").hover(
    function() { // mouse over
        get_span_from_image($(this)).show();
    },
    function() { // mouse out
        get_span_from_image($(this)).hide();
    }
);

希望对您有所帮助!

如果在每个 img 之后都有一个跨度,也许完全不使用 JavaScript 是个好主意? ;-)

您可以在 CSS 中使用 :hover 伪类,让您的东西始终可靠地工作。

考虑以下示例:

img + span {
  display: none;
}
img:hover + span {
  display: block;
}

/*/ Optional styles /*/
div {
  position: relative;
  float: left;
}
div img + span {
  position: absolute;
  color: #fff;
  background: #27ae60;
  border: solid 1px #2ecc71;
  border-radius: 50px;
  z-index: 1;
  bottom: 1em;
  width: 80%;
  left: 50%;
  margin-left: -43%;
  padding: 2% 3%;
  text-align: center;
}
<div>
  <img src="https://placehold.it/400x200">
  <span>This is an image of a gray rectangle!</span>
</div>

<div>
  <img src="https://placehold.it/200x200">
  <span>This is an image of a gray square!</span>
</div>

<div>
  <img src="https://placekitten.com/g/400/200">
  <span>This is an image of a cute kitten inside a rectangle!</span>
</div>

<div>
  <img src="https://placekitten.com/g/200/200">
  <span>This is an image of even cuter kitten inside a square!</span>
</div>