【问题标题】:transition with right using css?使用 css 正确转换?
【发布时间】:2022-01-06 14:14:04
【问题描述】:

我正在尝试使用 only 转换使框从左向右滑动 像这样:

#box {
  width: 150px;
  height: 150px;
  background: red;
  position:absolute;
  transition: all 2s ease-out;
  right:auto;

}

.active{
  background-color: green !important;
  right:0 !important;
}
<div id="box" onclick="this.classList.add('active')"></div>

但由于某种原因,盒子没有向右滑动

This 解决方案有效,但没有解释
有人可以解释为什么背景颜色转换但位置不正确吗?

【问题讨论】:

  • 在“自动”值上无法进行转换。你需要例如0 到 100% 之类的东西才能让它工作。在任何情况下都无法从 x 转换为 auto。

标签: javascript html css


【解决方案1】:

使用right: auto; 不起作用。

#box {
  width: 150px;
  height: 150px;
  background: red;
  position:absolute;
  transition: all 2s ease-out;
  right:100%;
  transform: translate(100%,0);

}

.active{
  background-color: green !important;
  right:0 !important;
  transform: translate(0,0) !important;
}
<div id="box" onclick="this.classList.add('active')"></div>

【讨论】:

  • 如果我们不知道宽度怎么办?例如,我将未知尺寸的图像加载到其中
  • @cakelover 在这种情况下,我假设您使用 Javascript 加载图像并且您可以重新计算右侧的位置。
  • nvm 我想通了,请检查您的编辑
【解决方案2】:

尝试改用animation 并添加关键帧,如下面的 sn-p 所示。

#box {
  width: 150px;
  height: 150px;
  background: red;
  position:absolute;
  animation: slide 2s forwards ease-out;
  right:auto;

}

  @keyframes slide {
    0% {
        transform: translateX(0);
    }
    100% {
        transform: translateX(50%);
    }
}
 <div id="box"></div>

【讨论】:

    【解决方案3】:

    您必须以 px 或 % 为单位指定框的“正确”属性,而不是“自动”。

    #box {
      width: 150px;
      height: 150px;
      background: red;
      position:absolute;
      transition: all 2s ease-out;
      right:calc(100% - 150px);   /* right is positioned to left by reducing the actual box width */
    
    }
    
    .active{
      background-color: green !important;
      right:0 !important;
    }
    <div id="box" onclick="this.classList.add('active')"></div>

    【讨论】:

    • 好吧,在这种情况下答案是正确的,但是如果我不知道盒子的宽度,例如我必须在其中加载图像,那该怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多