我对几个 block 的 jquery 效果有疑问。 Mouseenter 和 mouseleave 仅在第一个 div block 上起作用,而在所有其他 div block 上不起作用。
这是JS:
$(document).ready(function() { $('#mainbox').mouseenter( function () { $('#infobox').fadeIn(); }); $('#mainbox').mouseleave( function () { $('#infobox').fadeOut(); }); });
And also blocks:
<div id="mainbox"><div id="infobox" style="display: none;">first block - it works on this one</div></div>
<div id="mainbox"><div id="infobox" style="display: none;">2nd block - it doesn't work/div></div>
<div id="mainbox"><div id="infobox" style="display: none;">3rd block - it doesn't work</div></div>
你们知道问题出在哪里吗?
最佳答案
问题是:该选择器仅针对文档中第一个主框内的第一个信息框。
在API你可以阅读:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
这就是您的代码无法正常工作的原因。
提示: 将 id 切换到类并绑定(bind)鼠标事件以在 div 内搜索,例如:
$('.mainbox').mouseenter(
function () {
$(this).find('.infobox').fadeIn();
});
$('.mainbox').mouseleave(
function () {
$(this).find('.infobox').fadeOut();
});
关于javascript - 鼠标悬停问题和 jquery 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14648853/