jQuery使用animate创建循环
jQuery create loop with animate
我正试图将一个div向右滑动并使其循环。下面是我的代码jsfiddle的链接:
<head>
<meta charset="utf-8">
<title>animate demo</title>
<style>
div {
background-color: #bca;
width: 100px;
border: 1px solid green;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div id="block">Hello!</div>
<script>
function scroll() {
$( "#block" ).animate({marginLeft: "0.6in"},
{
duration: 1500,
complete: function() {
scroll
}
}
)};
scroll();
</script>
http://jsfiddle.net/ZWSPJ/
更新:
我很感激你的接受,但adeneo的回答要优雅得多。当他删除它时,我将在这里包括他的轮换方法:现场演示(点击)。
var $block = $('#block'); //I like to cache my references in advance
var flag = 0;
(function scroll() { //auto call this function with an IIFE
$block.animate({marginLeft: (flag) ? 0 : '0.6in'}, 1500, scroll);
flag ^= 1; //reverse flag
}());
其他方法:
现场演示(点击)。
var $block = $('#block'); //you can go ahead and cache this reference
function scroll() {
$block.css('marginLeft', 0); //reset margin
$block.animate({marginLeft: "0.6in"}, //animate margin
{
duration: 1500,
complete: function() {
scroll(); //repeat
}
}
)};
scroll(); //call function to begin loop
如果你想在每次跑步时反转动画,你可以这样做:
现场演示(点击)。
var $block = $('#block'); //you can go ahead and cache this reference
var animSwitch = 0;
function scroll() {
var margin = 0;
if (!animSwitch) {
margin = '0.6in';
animSwitch = 1;
}
else {
animSwitch = 0;
}
$block.animate({marginLeft: margin}, //animate margin
{
duration: 1500,
complete: function() {
scroll(); //repeat
}
}
)
};
scroll(); //call function to begin loop
所以一个正确的答案是:
function scroll() {
$( "#block" ).animate({marginLeft: "+=0.6in"},
{
duration: 1500,
complete: scroll
}
)};
scroll();
你想要这样的东西吗?
小提琴演示
function scroll() {
$("#block").animate({
marginLeft: "+=0.6in"
}, {
duration: 1500,
complete:scroll
})
};
scroll();
问题的一部分是
complete: function() {
scroll
}
这不会调用滚动函数,只调用包装函数。你需要做:
complete: function() {
scroll();
}
或更整洁的
complete : scroll
相关文章:
- 正在为循环创建唯一id
- 当从jquery的点击事件中的每个循环创建的数组到它之外时,它显示空白数组
- 基于循环创建变量
- 未捕获的类型错误:未定义不是函数,在中为循环创建了对象
- 如何在jquery中从$.each循环创建对象数组
- 使用jquery.ech()循环创建Object Key
- 如何在Parse.com SDK中循环创建多个对象
- Javascript 使用 For 循环创建动态表,其中包含要在其中显示的数组
- Javascript循环创建函数并使用收到的基于PHP Query的id附加值
- 在单击使用 for 循环创建的传单标记时给出操作
- Javascript 使用 for 循环创建具有唯一名称的数组
- 使用 Javascript for 循环创建 Javascript 数组
- 使用 for 循环创建一个数组数组
- 是否可以在 Javascript 中使用 for 循环创建多个函数
- 使用 jquery 在多个字母上为每个循环创建一个
- 为5x5表中的循环创建
- 使用for循环创建元素和事件侦听器
- 如何将“$(this)”传递给Slick.js插件(并使用循环创建多个旋转木马)
- jquery for循环创建多个按钮
- 我如何将代码后面的循环创建的Javascript函数组合为一个函数,这样我就不会'不必重复