【问题标题】:Adding class to transition element triggers too soon将类添加到过渡元素触发太快
【发布时间】:2013-01-08 20:43:20
【问题描述】:

我正在尝试为我的页面上的一些元素设置动画。我需要动画的属性之一是bottom,但是,我还需要能够在不动画的情况下重新定位元素,这就是为什么我向它添加了一个单独的类:.anim

.slideshow_footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    color: #fff
}
.slideshow_footer.anim {
    -webkit-transition:bottom 0.3s ease-out;
    -moz-transition:bottom 0.3s ease-out;
    -o-transition:bottom 0.3s ease-out;
    -ms-transition:bottom 0.3s ease-out;
    transition:bottom 0.3s ease-out;
}

在我的 Javascript 中,我执行以下操作:

var footer = $('#footer');
// do some magic with the footer
// ...
// ...
setCss(footer, 'bottom', -100); // position it so it's hidden, this should be immediate
addClass(footer, 'anim'); // add the animation class
setCss(footer, 'bottom', ); // animate the footer sliding in

请注意,我没有使用 jQuery 或其他任何东西,它是一个内部 javascript 框架。

我找到了解决问题的解决方法,但它非常难看:

var footer = $('#footer');
// do some magic with the footer
// ...
// ...
setCss(footer, 'bottom', -100); // position it so it's hidden, this should be immediate
addClass(footer, 'anim'); // add the animation class
setTimeout(function() {
    setCss(footer, 'bottom', ); // animate the footer sliding in
}, 0); // even no timeout works...

谁能向我解释发生了什么以及如何最好地解决这个问题?可能更改 addClass 和 setCss 函数?

【问题讨论】:

  • addClasssetCss 函数中有什么?
  • addClass 和 setCss 是基本的包装函数,具有与 jQuery 类似的功能。他们按照上面所说的去做:他们向一个元素添加一个类(检查它是否已经存在)并 setCss 设置一个元素的样式(如果可能,它有一些 if's 来捕获一些异常)。
  • 我猜的差不多了,但我希望在setCss 函数中找到某种“延迟”:P
  • 在整个 JavaScript 完成之前,浏览器不会更新可见的 HTML。如果是这样,在“底部”之后设置“右”会移动元素两次。从浏览器的角度来看,元素立即获得“动画”和底部未定义(?)。 setTimeout 和 0 timeout 告诉浏览器尽快执行代码,但不是在同一轮 JavaScript 中。我说你的解决方法很好。
  • 我同意@Odalrick。您的解决方法甚至不接近“丑陋”,它实际上被许多人采用为运行代码的“异步”方式。

标签: javascript css css-transitions


【解决方案1】:

回答我自己的问题:

使用 timeOut 是正确的方法。

在整个 JavaScript 完成之前,浏览器不会更新可见的 HTML。如果是这样,在“底部”之后设置“右”会移动元素两次。从浏览器的角度来看,元素瞬间获得了“anim”和bottom 0。setTimeout和0 timeout告诉浏览器尽快执行代码,但不是在同一轮JavaScript中。 p>

这种变通方法实际上被许多人采用为“异步”运行代码的方式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2018-07-23
    相关资源
    最近更新 更多