用CSS转换平滑javascript驱动的快速位置变化



我认为这是一个很渺茫的机会,但值得一问。我在许多移动应用程序(例如Facebook)中有类似的左侧菜单,当你按下"打开"按钮时,它会平滑地打开(在我的例子中,使用CSS过渡),但我也实现了一个拖拽功能,你可以从屏幕左侧滑动将菜单拖出。在这种情况下,它是由javascript驱动的,而且速度太快(看起来太快),以至于CSS转换不知道该怎么做。它会变得混乱,口吃,倒退等等。所以我只是在用户拖出菜单时关闭了过渡。这在iOS上运行得非常好,因为它非常流畅,而Android和黑莓都在尽最大努力,如果它能更流畅就更好了。

这是我的CSS打开/关闭菜单状态
#view_wrap {
    position: absolute;
    top: 0px;
    right: -100%;
    left: 100%;
    bottom: 0px;
    -webkit-transition: all .2s 0s;
    -webkit-transform: translate(-100%);
    background-color: #fff;
}
#menu.open + #view_wrap {
    -webkit-transform: translate(-3.125em);
    box-shadow: 0px 0px .3125em rgba(0,0,0,.5);
    overflow: hidden;
}
#view_wrap.animating {
    -webkit-transition: none;
}

和拖动功能只是改变translate值与每个touchmove

你知道有或没有CSS过渡的情况下,有什么技巧可以让如此快速的变化更顺利地应用吗?

我设法让这个工作,不完全确定它是否会在你的情况下工作,但我有一个幻灯片,通过下一个&后退按钮和手指拖动。

我也遇到过类似的情况,按钮的滑动是由3d过渡驱动的,所以在任何支持它的设备上都非常平滑,但是拖动是用旧的javascript完成的,而且很口吃。

我有比这更多的代码,但为了清晰起见,只是提取了与过渡相关的位。

在被拖拽的元素上,我开始使用jquery在touchstart事件上添加一个小持续时间的过渡,100毫秒似乎对我来说很好。

// inside the touchstart event
$('#my-element').on('touchstart', function(e) {
      $(this).css('transition','100ms');
});

当touchmove事件触发时,我之前正在计算左手位置并设置元素的左位置,我通过应用3d过渡并在用户移动手指时更新X坐标来取代它。注意:translate3d在iOS设备上显然是"硬件加速"的,而"translate"则不是,所以最好使用Y &Z设置为0

// Inside the touchmove event, -10px will change as the user drags
$('#my-element').on('touchmove', function(e) {
   var newLeft = /** A calculation of the new left hand position **/
   $(this).css('transform','translate3d('+newLeft +'px,0px,0px);
});

最后,在touchend事件中,我删除了CSS过渡,并将元素的左侧位置重新设置为正确的位置。

// Inside the touchend event
$('#my-element').on('touchend', function(e) {
   var endLeft = /** A calculation of the new left hand position **/
   $('#sliding-element').css('transition','');
   $('#sliding-element').css('transform','');
   $('#sliding-element').css('left', endLeft /** Whatever the new left hand position is **/);
});

希望能有所帮助

最新更新