首页 > 社区问答列表 >当切换属性使用时,我能保持CSS过渡吗?

  当切换属性使用时,我能保持CSS过渡吗?

我有一个div从左到右移动。为了使它始终在屏幕上,并且在窗口调整大小时永远不会对齐,我根据屏幕的哪一侧最接近来切换左和右的使用。

发生的事情是,只要用户在屏幕的同一侧来回移动div(也就是说,div仍然面向相同的属性),我用于改变左右属性的CSS过渡就能顺利工作,但是一旦方向从左向右切换或反之亦然,就没有过渡,div只是立即移动。

即使在使用左和右之间切换,我如何维护我拥有的CSS转换(或我没有的类似CSS转换)?

我在javascript中有这个函数:


function moveTimeline(screenIndex) {
    // possibly variable because of window resize
    let timelineSectionWidth = (TIMELINE_BACKGROUND_WIDTH - documentElement.clientWidth) / num_timelinePieces;
    // check what side the div is supposed to be attached to
    let isOnLeftSide = (screenIndex < num_timelinePieces / 2);
    // reverse the index if it's on the right side
    if (!isOnLeftSide)
        screenIndex = screenIndex - num_timelinePieces;
    // calculate new pixel position
    let new_timelinePosition = Math.floor(screenIndex * timelineSectionWidth);

    // unset the unused properties so they don't interfere
    if (isOnLeftSide) {
        timelineBackground.css({
            "left": "-" + new_timelinePosition + "px",
            "right": "auto"
        });
    } else {
        timelineBackground.css({
            "left": "auto",
            "right": (new_timelinePosition) + "px"
        });
    }
}

css的属性是:

transition: left 1s ease, right 1s ease;

我希望div继续从左到右平滑地移动,即使在切换哪个属性是自动驾驶,但这并没有结束工作。不知道如何从这里开始。我真的宁愿不使用单个属性,因为如果窗口被调整大小,这会弄乱div的位置,手动一步一步地移动div绝对是最后的手段。

P粉465675962
P粉465675962

  • P粉038161873
  • P粉038161873   采纳为最佳   2023-08-03 17:11:29 1楼

    当你从右到左切换时,你的过渡似乎会迅速转移到另一边的原因是因为你将左和右设置为自动值。CSS转场(或者一般的CSS动画)不适用于带有auto值的道具。

    这是来自文档使用CSS过渡:

    也许你会更好地使用转换CSS属性与translateX()函数而不是左/右CSS道具?这样做将为您提供一个单一的、可靠的CSS值来转换,并提高性能。

    你的代码可能看起来像这样:


    function moveTimeline(screenIndex) {
    
      ...
    
      if (isOnLeftSide) {
          timelineBackground.css({
             "transform": `translateX(-${new_timelinePosition}px)`
          });
      } else {
          timelineBackground.css({
              "transform": `translateX(${new_timelinePosition}px)`
          });
      }
    }
    

    你的CSS过渡看起来像这样:

    transition: transform 1s ease;
    

    H应该有用

    +0 添加回复