你们能明白为什么以下内容会导致 IE 崩溃吗?我必须基本上注释掉所有内容,最终发现这是导致崩溃的原因,更具体地说,当 .addClass 和/或 .removeClass 在 if 条件内运行时:
if ( percentExpenses > 50 && percentExpenses < 80 ) {
$('.progress-bar-expenses')
.removeClass('progress-bar-success')
.addClass('progress-bar-warning');
} else if ( percentExpenses >= 80 ) {
$('.progress-bar-expenses')
.removeClass('progress-bar-success progress-bar-warning')
.addClass('progress-bar-danger');
} else {
$('.progress-bar-expenses')
.addClass('progress-bar-success');
}
我只是添加旧的引导进度条属性。这些属性之一是否会导致问题?
.progress-bar-danger {
background-color: #dd514c;
background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35));
background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35);
background-image: -o-linear-gradient(top, #ee5f5b, #c43c35);
background-image: linear-gradient(to bottom, #ee5f5b, #c43c35);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0);
}
实例: http://jsfiddle.net/Hs37H/1/
在 Windows 7 上使用 IE11
最佳答案
这里没有任何内容一定会导致 Internet Explorer 崩溃,但是完全有可能这些类之一添加的过渡或动画本身会导致 Internet Explorer 崩溃。在 中,我看到过类似 transition: all 1s
导致 Chrome 和 Internet Explorer 崩溃的情况。
除了这种可能性之外,这里没有什么必然会导致浏览器崩溃。
更新以下演示评论
以下几行似乎导致 Internet Explorer 9、10 和 11 中的卡住(8 不受影响):
$('.progress').bind("DOMSubtreeModified",function(){
percentage();
});
$('.table').bind("DOMSubtreeModified",function(){
loadChart();
});
这里的问题是,第一个函数向元素添加类,触发 DOMSubtreeModified
事件,该事件调用 percentage()
,添加类,从而触发 DOMSubtreeModified
事件,这......你明白了,对吧?
如果您访问了 Mozilla Developer Network documentation for this event ,您将阅读以下内容:
Be very careful with this event it is easy to cause an infinite loop if you decide to change the DOM inside the event handler.
您的事件处理程序实际上通过添加和/或删除类来更改 DOM。您的 loadChart()
方法添加或删除 Canvas 元素,这可能会触发进一步的 DOMSubtreeModified
事件
解决方案
此问题的解决方案是在需要运行 percentage
或 loadChart
时通知应用程序。您可以通过使用 jQuery 的 .trigger
方法并订阅自定义事件来完成此操作:
$(".progress").on("percentage", percentage);
$(".table").on("loadChart", loadChart);
在上面的示例中,当 .progress
上触发自定义“percentage”事件时,我们将通过调用 percentage
函数进行响应。对于 loadChart
事件和函数也是如此。现在剩下的就是我们自己触发这些事件:
function doSomethingMagical ( ajax ) {
ajax.success(function () {
// This results in the calling of function:percentage
$(".progress").trigger("percentage");
});
}
关于导致 IE 卡住的 JavaScript 代码(.addClass 和 .removeClass),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20714601/