切换浏览器选项卡时JavaScript动画不起作用
现场直播: 我正试图通过jQuery实现旋转木马效果。请注意,为了更好地了解情况,您必须降低窗户高度 问题是:如果您继续查看页面,旋转木马运行良好,但如果切换到另一个浏览器选项卡,等待几秒钟,然后切换回,您将看到旋转木马被替换。您在其他浏览器选项卡上停留的时间越长,它被替换的位置就越多 问题似乎来自此功能:切换浏览器选项卡时JavaScript动画不起作用,javascript,jquery,css,Javascript,Jquery,Css,现场直播: 我正试图通过jQuery实现旋转木马效果。请注意,为了更好地了解情况,您必须降低窗户高度 问题是:如果您继续查看页面,旋转木马运行良好,但如果切换到另一个浏览器选项卡,等待几秒钟,然后切换回,您将看到旋转木马被替换。您在其他浏览器选项卡上停留的时间越长,它被替换的位置就越多 问题似乎来自此功能: function getRelativeClientRect(el) { var rect = el.getBoundingClientRect(), parentRect
function getRelativeClientRect(el) {
var rect = el.getBoundingClientRect(),
parentRect = el.offsetParent.getBoundingClientRect();
return {
bottom: parentRect.bottom - rect.bottom,
height: rect.height,
left: rect.left - parentRect.left,
right: parentRect.right - rect.right,
top: rect.top - parentRect.top,
width: rect.width
};
}
我从这个问题中得到了答案:
以下是我的网站的HTML和代码:
HTML:
JS:有两个相关的JS脚本,第一个位于关闭body标记之前,我使用它使图像自动适应屏幕高度
<script>
(function(){
var width, height = true;
function initHeader() {
headerHeight = document.getElementById('rt-header')? document.getElementById('rt-header').getHeight():0;
width = window.innerWidth;
height = window.innerHeight - headerHeight;
largeHeader = document.getElementById('rt-topfullwidth');
largeHeader.style.height = height+'px';
j('.marquee-container').height(height);
j('.marquee-container .image').height(height);
}
// Main
initHeader();
})();
</script>
第二个位于,我使用它来实现旋转木马效果。我知道它的可读性很低,所以我给它添加了一些注释。在在线查看网站上的行为后,我的最佳选择是浏览器在选项卡不可见时不播放所有转换帧,从而优化CPU,并在选项卡再次可见时赶上当前帧,这会导致屏幕上出现闪烁 强化这一理论的是,该漏洞发生在Chrome上,而不是Firefox上
我认为解决这个问题的一个可能办法是用JavaScript而不是CSS实现动画。。。或者等待Chrome解决问题。我认为问题在于setTimeout和setInterval。如果切换到其他选项卡,Chrome无法正确跟踪setTimeout和setInterval的计时器。我想这是为了提高浏览器的性能,但在这种情况下,这显然不是你想要的。我不认为chrome团队打算“修复”这个问题 看这里:如果你提到的“bug”指的是我遇到的问题,我在firefox上有它,它确实有。在控制台中设置一个运行日志的间隔,即使在切换选项卡时,您也会看到日志弹出
.marquee-container{position:relative;overflow:hidden}
.image-container{position:absolute;transition:all 1s ease; display: -webkit-box;display: -moz-box;display: -ms-flexbox;display: -webkit-flex;display: flex;}
.image{float:left;background-size:cover;cursor:pointer}
<script>
(function(){
var width, height = true;
function initHeader() {
headerHeight = document.getElementById('rt-header')? document.getElementById('rt-header').getHeight():0;
width = window.innerWidth;
height = window.innerHeight - headerHeight;
largeHeader = document.getElementById('rt-topfullwidth');
largeHeader.style.height = height+'px';
j('.marquee-container').height(height);
j('.marquee-container .image').height(height);
}
// Main
initHeader();
})();
</script>