即使控制台日志给出 while 表达式为 false,循环也会无限运行。
var tile_height;
$(document).ready(function(){
tile_height = $("#department > .front").height();
});
function tile_animate(e){
console.log(($('> .front',e).css("height") > '0px') && ($('> .back',e).height() < tile_height));
while(($('> .front',e).css("height") > '0px') && ($('> .back',e).height() < tile_height))
{
$('> .front',e).animate({height: '-=1px'});
$('> .back',e).animate({height: '+=1px'});
}
}
我尝试过将 if 语句用作递归函数,但这也行不通。使用 while 会导致浏览器停止响应。调用该函数的html代码为
HTML代码
<div class="tiles" id="gallery" onmouseover="javascript:tile_animate(this)">
<div class="front">
</div>
<div class="back">
</div>
</div>
最佳答案
问题是您在悬停时使用了循环。更好的是,您在样式中使用 jQuery 动画并在必要时应用它。
但是,按照您描述问题的方式,看起来您将缩小一次 div - 之后没有任何东西可以恢复它。 我注意到 div 被命名为“部门”,但 JavaScript 正在寻找“画廊”——所以我改变了它……
因此,为了在您现在拥有代码的情况下执行此操作,需要进行一些调整:
移除 while 循环并在悬停时执行检查。
检查是为了查看动画是否已经发生。
如果正在播放动画,请忽略悬停。
如果动画还没有出现,设置一个标志表明它已经出现,并执行所需的动画 - 不要逐像素减小 div 的大小(这是动画为您所做的)。
完成后,div 的高度将为 0px(并且不能再次悬停)。
如果你想稍后恢复 div,那么在动画之前存储它的原始尺寸,并在需要时恢复它们(不要忘记重置 inLoop 变量)...
var tile_height;
var inLoop = false;
$(document).ready(function() {
tile_height = $("#gallery > .front").height();
});
function tile_animate(e) {
if (!inLoop && ($('> .front', e).css("height") > '0px') && ($('> .back', e).height() < tile_height)) {
inLoop = true;
$('> .front', e).animate({
height: '0px'
});
$('> .back', e).animate({
height: tile_height
});
}
}
关于Javascript 导致浏览器挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33194776/