Javascript 导致浏览器挂起

标签 javascript jquery html

即使控制台日志给出 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/

相关文章:

javascript - Php Javascript 从 while 循环中显示的数据库中删除文件

javascript - 如何在从 json 数据创建 html 表时创建隐藏的 <td> 行?

html - 一些 img 标签的 last-of-type 问题

javascript - 如何根据两个分隔符拆分字符串?

javascript - 如何使用 JavaScript 滚动到目标 html 部分的垂直中心?

html - haml 文件中的 yaml 前端内容

使用 setTimeout() 方法在一段时间内更改背景颜色的 Javascript 函数

javascript - jQuery when() 似乎不适用于each()

javascript - ASP.NET MVC 编辑器用于自定义 javascript

jquery - 如何为三个选项卡中的每个表格制作不同的重复颜色?