【问题标题】:Transition to and from position Auto转换到和从位置自动
【发布时间】:2015-07-23 13:12:57
【问题描述】:

一个元素被任意放置在页面上,并且需要转换到事件的固定位置(在我的例子中是屏幕滚动,但我在小提琴中使用悬停)

元素的原始位置以父元素为中心(顶部:自动,左侧:自动)。悬停时,它应该平滑地移动到屏幕的角落(左:0,上:0),然后返回。相反,它只是原地跳转,忽略了转换属性。

我意识到没有一个浏览器支持自动转换,但希望找到一些解决方法。

fiddle

<div>
    <span>test</span>
</div>

div {
    border: 1px solid red;
    text-align: center;
    height: 100px;
    margin: 15px;
}
span {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: blue;
    transition: all 1s;
    position: fixed;
    left: auto;
    top: auto;
}
div:hover span {
    left: 0;
    top: 0;
}

附言。我希望只修复 css,但使用 JQuery 的解决方案也可以。

【问题讨论】:

  • 问题在于您的left:auto;right:auto;。我正在研究为什么这可能会导致转换覆盖。
  • 我希望修复 css,但 jquery 解决方案也可以工作

标签: jquery html css


【解决方案1】:

您是正确的,现代浏览器无法转换为“自动”。你可以使用 CSS 来实现你想要的。

在您的示例中,您需要通过更改来居中

top: auto;
left: auto;

vertical-align: top;
left: calc(50% - 25px);

从 span 和 span:hover 中移除 top 属性,并将其替换为 vertical-align。

JSFiddle Example

【讨论】:

  • top: 0 怎么样?该项目需要附加到屏幕顶部,然后与 div 一起返回到原始位置。如果 div 大到可以滚动,原来的 'top' 不能设置为数字。
【解决方案2】:

为什么不设置一个具体的topleft?你有span{position: fixed},所以在这种情况下你总是知道你的toprightbottomleft(相对于视口)。

所以试试吧:

div {
    border: 1px solid red;
    text-align: center;
    height: 100px;
    margin: 15px;
}
span {
    display: inline-block;
    width: 50px;
    height: 50px;
    background: blue;
    transition: all 1s;
    position: fixed;
    left: 50%;
    margin-left: -25px; /*or transform: translateX(-50%) if you don't know the width of span*/
    top: 16px;
}
div:hover span {
    left: 0;
    top: 0;
    margin-left: 0; /*or transform: none if you don't know the width of span*/
}
<div>
    <span>test</span>
</div>

您可以根据需要更改top left 来实现您想要的。

Here a jsfiddle example to play with

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2020-09-26
    • 2011-08-02
    • 1970-01-01
    • 2014-01-27
    相关资源
    最近更新 更多