mom*_*loo 3 javascript css jquery animation jquery-animate
我有一个带有长内联文本的元素,并且想要制作动画,将该文本从屏幕外右侧(窗口右边框后面的整个文本)移动到屏幕左侧。
我的想法是通过将 margin-left 设置为元素的减号(宽度)来移动元素:
var element = $(this);
$("p").animate({
'marginLeft': - element;
}, 4000);Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
但这是行不通的。有任何想法吗?
据我所知,在这种情况下,$(this)就是窗户。您想要为其$("p")本身设置动画,并且需要指定根据其宽度而不是一般 DOM 元素进行动画处理。;您发送给函数的对象中也存在流氓行为animate(您可以在开发人员工具控制台中看到类似的错误)。
var $element = $("p");
$element.animate({
'marginLeft': -($element.outerWidth())
}, 4000);Run Code Online (Sandbox Code Playgroud)
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%;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
编辑
或者,这里是纯 CSS。如果您正在开发的浏览器支持它,那么这是更有效的途径。它使浏览器“重绘”更少,并且像 JS 那样在 GPU 上运行而不是在 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+ */
}Run Code Online (Sandbox Code Playgroud)
<p>element with long long long long inline text....</p>Run Code Online (Sandbox Code Playgroud)