如果鼠標位於div或任何div
的嵌套元素上,我想要顯示一個工具欄。但是下面的jQuery 1.7解決方案只有在鼠標經過div
時纔有效,只有在item
css類中添加padding
纔有可能。在div上處理mouseenter/mouseleave和在jQuery中嵌套元素
<head>
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<style type="text/css">
.toolbar { display: none; }
.item { padding: 1px; } /* doesn't work without padding! */
</style>
<title>Demo</title>
</head>
<body>
<div class="section">
<div class="item">
<p class="toolbar">TOOLS</p>
<p>content</p>
</div>
<div class="item">
<p class="toolbar">TOOLS</p>
<p>content</p>
</div>
</div>
<script type="text/javascript">
$(".section").on(
"mouseenter",
".item",
function(event) {
$(event.target).children('.toolbar')
.show(100);
}
)
$(".section").on(
"mouseleave",
".item",
function(event) {
$(event.target).children('.toolbar').hide();
}
)
</script>
</body>
1px的的填充不會如此糟糕,但它會導致更大的填充在頂部和底部,這種解決方法不能正常工作 - 特別是如果鼠標從左側或右側進入。
如何處理沒有填充技巧的mouseenter
和mouseleave
事件?
我知道@ ManseUK發佈了正確的答案,但我只是想添加一個關於填充技巧的快速筆記。這工作(大部分時間),因爲添加填充停止[邊緣崩潰](http://www.w3.org/TR/css3-box/#collapsing-margins),所以事件可以觸發'.item '(其中'event.target'顯然是你想要的)以及'p's。 – meloncholy