用动画从左到右浮动图像?

Float image from left to right with a animation?

我有一个汉堡包(三个水平条)图标,我想将其从 float: left 更改为 float:right,但动画要流畅。

我不能使用 jQuery 但我可以使用 JavaScript 所以我有这个小功能可以在单击图像时更改浮动状态:

var menuButton = document.getElementById('menu-button');


menuButton.onclick = function () {

    menuButton.style.float =  "right";
}

这是可行的但不是流畅的动画我怎样才能使它成为流畅的动画?

一个运行演示:

var menuButton = document.getElementById('menu-button');


menuButton.onclick = function () {

    menuButton.style.float =  "right";
}
   nav {
        background: pink;
        height: 60px;
    }

    nav #menu-button {
        margin: 20px 24px;
        display: inline;
        float: left;
    }
    <nav id="nav-bar">
        <a href="#/index"><img id="menu-button"alt="menu icon" src="images/toggle-open.svg"></a>
    </nav>

不幸的是,改变从左到右的浮动不能用任何当前技术简单地制作动画,因为动画需要一个相对锚点来执行计算。

您可以做的是将相对左浮动位置设置为近似右浮动位置(例如,通过增加左边距),并在完成后更改为右浮动。但实际上,最后一步不是必需的,除非要处理页面未来的布局更改(例如 window 调整大小,对于流宽网站)。

我能够使用 CSS3 转换和 marginLeft 来完成这项工作。

在 parentElement.parentElement 中有一些技巧(爬上 DOM 树的两层),在 -44px 中考虑了图标宽度加上边距宽度,但是如果你想要到,你可以为这些编写更复杂的编码解决方案(动态处理元素的实际宽度/边距)。

var menuButton = document.getElementById('menu-button');
menuButton.onclick = function () {
    var left = menuButton.parentElement.parentElement.clientWidth - 44;
    menuButton.style.marginLeft =  left+"px";
    window.setTimeout(function() {
        menuButton.style.float =  "right";
    }, 1000);
}
nav {
    background: pink;
    height: 60px;
}

nav #menu-button {
    margin: 20px 24px;
    display: inline;
    float: left;

    /* Width and height hack to represent missing image's height and width */
    width: 20px;
    height: 20px;

    /* CSS Transition added */
    -webkit-transition: margin-left 1s;
    transition: margin-left 1s;
}
<nav id="nav-bar">
    <a href="#/index"><img id="menu-button"alt="menu icon" src="images/toggle-open.svg"></a>
</nav>

如果您知道容器的宽度,请不要使用 float 属性,而是 margin-left :

a {
  margin-left: 0;
  transition: margin-left 1s ease-in-out;
}
a.right{
  margin-left: 400px; /* change for good value */
}

然后使用 javascript

right class 添加到您的 a 元素

https://jsfiddle.net/rd4h4s5h/

我会这样做:

<style>
nav {
    position: relative;
}

nav a {
    position: absolute;
    left: 0;
    transition: left 1s linear;
}
</style>



<nav id="nav-bar">
    <a id="box" href="#/index"><img id="menu-button" alt="menu icon" src="images/toggle-open.svg"></a>
</nav>



<script>
    const navBar = document.getElementById("nav-bar");
    const box = document.getElementById("box");
    const menuButton = document.getElementById("menu-button")

    menuButton.addEventListener("click", (e) => {
       box.style.left = (navBar.offsetWidth - box.offsetWidth) + "px";
    });
</script>