如何为一个项目制作不同的动画
How to make on toggle different animation to an item
我想在您单击左栏时将其动画化为 CSS left
10,当我再次单击它时返回默认值 CSS。
我试过这段代码:
$('.left-bar').click(function() {
$('.left-bar').toggle(function () {
$(this).animate({
// style change
left: "-116x"
}, 500);
}, function () {
$(this).animate({
// style change back
left: "-185px"
}, 500);
});
}
除了使用 .toggle
,您还可以执行如下操作。该示例基于 .animate
。
在示例中,我使用 .data
来存储元素 isToggled
的状态。基于这些数据,我可以弄清楚我是否可以进入一个状态并回到之前的状态。
var $leftBar = $('.left-bar');
$leftBar.click(function() {
var isToggled = $leftBar.data('toggled'); // get data
var action = isToggled ? "+=100px" : "-=100px";
$leftBar.animate({ "left": action }, 500);
$leftBar.data('toggled', !isToggled); // set the opposite state of current one
});
.left-bar {
position: absolute;
background-color: blue;
width: 50px;
height: 50px;
left: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-bar"></div>
备注:
这个 "left":"+=100px"
将 100px 添加到现有的左侧变量(例如,如果 left = 100
那么结果将是 left += 100px = 200px
)。 -=100px
表示减去 100px(例如,如果 left = 100
那么结果将是 left -= 100px = 0px
)。
我没有使用 .toggle()
因为它按照文档中的说明进行操作:
Display or hide the matched elements
并且您想更改css 元素不隐藏和显示。
我想在您单击左栏时将其动画化为 CSS left
10,当我再次单击它时返回默认值 CSS。
我试过这段代码:
$('.left-bar').click(function() {
$('.left-bar').toggle(function () {
$(this).animate({
// style change
left: "-116x"
}, 500);
}, function () {
$(this).animate({
// style change back
left: "-185px"
}, 500);
});
}
除了使用 .toggle
,您还可以执行如下操作。该示例基于 .animate
。
在示例中,我使用 .data
来存储元素 isToggled
的状态。基于这些数据,我可以弄清楚我是否可以进入一个状态并回到之前的状态。
var $leftBar = $('.left-bar');
$leftBar.click(function() {
var isToggled = $leftBar.data('toggled'); // get data
var action = isToggled ? "+=100px" : "-=100px";
$leftBar.animate({ "left": action }, 500);
$leftBar.data('toggled', !isToggled); // set the opposite state of current one
});
.left-bar {
position: absolute;
background-color: blue;
width: 50px;
height: 50px;
left: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-bar"></div>
备注:
这个
"left":"+=100px"
将 100px 添加到现有的左侧变量(例如,如果left = 100
那么结果将是left += 100px = 200px
)。-=100px
表示减去 100px(例如,如果left = 100
那么结果将是left -= 100px = 0px
)。我没有使用
.toggle()
因为它按照文档中的说明进行操作:
Display or hide the matched elements
并且您想更改css 元素不隐藏和显示。