将 marginLeft 动画化为元素的 -width

Animate marginLeft to element's -width

我有一个带有长内联文本的元素,我想制作动画,将此文本从屏幕右侧(window 右边框后面的整个文本)移动到屏幕左侧。

我的想法是通过将 margin-left 设置为元素的负(宽度)来移动元素:

var element = $(this);
$("p").animate({
  'marginLeft': - element;
}, 4000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>element with long long long long inline text....</p>

但这不起作用。有什么想法吗?

在那种情况下,据我所知,$(this) 就是 window。您想要对 $("p") 本身进行动画处理,并且您需要根据其宽度而不是一般的 DOM 元素来指定您要进行动画处理。您发送到 animate 函数的对象中也有一个流氓 ;(您可以在开发人员工具控制台中看到类似这样的错误)。

var $element = $("p");

$element.animate({
  'marginLeft': -($element.outerWidth())
}, 4000);
body {
  margin: 0;
  font-family: sans-serif;
  font-size: 12px;
  overflow-x: hidden; /* no horizontal scrollbar */
}
p {
  white-space: nowrap;
  background: #ccc;
  display: inline-block;
  margin-left: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>element with long long long long inline text....</p>

编辑

或者,这里是纯CSS。如果您正在开发的浏览器支持它,那么这是更有效的途径。它使浏览器 "repaint" 更少,并且在 GPU 上运行而不是像 JS 那样在 CPU 上运行。

body {
  margin: 0;
  font-family: sans-serif;
  font-size: 12px;
  overflow-x: hidden; /* no horizontal scrollbar */
}

@-webkit-keyframes offscreenLeft {
  0%   { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}
@-moz-keyframes offscreenLeft {
  0%   { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}
@-o-keyframes offscreenLeft {
  0%   { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}
@keyframes offscreenLeft {
  0%   { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}

p {
  white-space: nowrap;
  background: #ccc;
  display: inline-block;
  padding-left: 100%; /* translate uses the inner width of the p tag, so the thing pushing it offscreen needs to be *inside* the p, not outside (like margin is) */
  
  -webkit-animation: offscreenLeft 4s forwards; /* Safari 4+ */
  -moz-animation:    offscreenLeft 4s forwards; /* Fx 5+ */
  -o-animation:      offscreenLeft 4s forwards; /* Opera 12+ */
  animation:         offscreenLeft 4s forwards; /* IE 10+, Fx 29+ */
}
<p>element with long long long long inline text....</p>

如果我是你,我会在元素上切换 class 并使用 CSS 的 transform: translateX() 结合 transition 将元素移出屏幕。

codepen

css

p {
  transform: translateX(0);
  transition: transform 0.3s ease;
}

p.off-screen-right {
  transform: translateX(100%)
}

js

$(document).ready(function () {
  $('button').click(function () {
    $('p').toggleClass('off-screen-right')
  })
})

步骤

  • 获取 <p> 宽度并将其保存在变量中。
  • 然后,将初始的 margin-left 设置为 $(window).width()
  • 之后,您可以调用animate函数将margin-left设置为您最初保存在变量中的宽度的负值

工作代码

$(function() {
  var width = $("p").width();
  
  $("p")
    .css('margin-left', $(window).width())
    .animate({ 'margin-left': -width }, 4000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>element with long long long long inline text....</p>