【发布时间】:2015-08-08 22:32:48
【问题描述】:
我正在尝试做一些相当简单的事情。我想从图像后面滑出一个菜单,并让它在过渡时淡入淡出。
因此,默认菜单的 z-index 设置为 -1,图像设置为 1。
当您将鼠标悬停在表格上时,我会为幻灯片设置动画并具有超时功能,将菜单的 z-index 更改为 2。当您将鼠标离开表格时,我将 z-index 设置回 -1 并为过渡设置动画图片后面。
这应该有效,而且有时会有效。我注意到,特别是如果我将 mouseover 设置为悬停,有时当鼠标不在它设置的桌子附近时,mouseover\hover 函数会在 mouseleave 触发后触发。
所以最终发生的情况是,有时 z-index 没有正确更改,您可以看到菜单在图像转换时出现在图像前面。有时它仍然可以正常工作。你会认为它每次都会以相同的方式工作,无论好坏。
我尝试了不同的方法。我正在使用超时,因为当后一个动画完成时,很难保持两个非排队动画运行,同时运行一个函数。
这是我的代码:
<script type="application/javascript">
$( document ).ready(function() {
$("#headerTable").mouseover(function(){
$("#movableMenu")
.animate({top: "0px"}, {duration: 750, queue:false})
.animate({opacity: "1"}, {duration: 1500, queue:false});
setTimeout(function() {
console.log("Out: " + $("#movableMenu").css('z-index'));
$("#movableMenu").css('z-index', 2);
console.log("Out: " + $("#movableMenu").css('z-index'));
}, 1500);
});
$("#headerTable").mouseleave(function() {
console.log("In: " + $("#movableMenu").css('z-index'));
$("#movableMenu").css('z-index', -1);
$("#movableMenu")
.animate({top: "-55px"}, {duration: 750, queue:false})
.animate({opacity: "0"}, {duration: 1500, queue:false});
console.log("In: " + $("#movableMenu").css('z-index'));
});
$(".menuItem").hover(function(){
$(this).css('color', 'teal');
$(this).css('font-size', '18');
$(this).css('font-weight', 'bold');
});
$(".menuItem").mouseout(function(){
$(this).css('color', 'black');
$(this).css('font-size', '16');
$(this).css('font-weight', 'normal');
});
});
</script>
</head>
<body>
<table id="headerTable" align="center" border="1">
<tr>
<td><img width="600px" height="225px" src="images/heading2.png" style="z-index:2" /></td>
</tr>
<tr>
<td>
<div id="movableMenu" style="width:100%; height:50px; position:relative; top:-55px; z-index:-1; opacity:0">
<span class="menuItem">Home</span><span class="menuItem">Bio</span><span class="menuItem">Media</span><span class="menuItem">Scores</span><span class="menuItem">Lessons</span><span class="menuItem">Repertoire</span><span class="menuItem">Contact</span><span class="menuItem">Links</span>
</div>
</td>
</tr>
</table>
【问题讨论】:
-
你能设置一个小提琴吗?从第一次查看您的代码开始,您就使用了 setTimeout,但我认为您希望使用完整的函数而不是使用 2 个单独的计时器。还有一个 .stop() 你可以调用,以防你在原始动画结束之前将鼠标悬停在鼠标悬停
-
为什么不为此使用 CSS 过渡?
-
一些想法。您必须将
position: relative添加到您的图像中才能真正应用与默认值不同的 z-index。另外,我建议不要更改 z-index 属性,而是通过translate3d更改translateZ属性。你可以看看这个问题:stackoverflow.com/questions/27302395/… -
这里是小提琴,按要求:jsfiddle.net/4tuwbyvn
-
@Imgonzalves 我以前没有使用过 CSS 过渡。简单看一下它们,看起来我可以让它与自身相关,我可以让它与其他东西相关吗?我必须将鼠标悬停在图像上才能告诉它移动菜单。如果只是将鼠标悬停在菜单上以告知菜单更改,那将很容易。
标签: jquery css animation z-index