[英]How to toggle style in animation using jQuery?
How can I add opacity: 0.5
to li
when it's clicked and toggle the opacity back to opacity:1
when clicked again with animation? 如何在单击时将
opacity: 0.5
添加到li
并在再次单击动画时将opacity:1
切换回opacity:1
?
$('li').on('click', function () {
$(this).animate({
opacity: 0.5
}, 500, function () {
$(this).toggleClass('completed');
});
});
Is there any simple solution like toggling between classes or do I need to add logic to check the current opacity and change accordingly? 是否有任何简单的解决方案,例如在类之间进行切换,还是需要添加逻辑来检查当前的不透明度并进行相应的更改? I don't want to change markup or CSS but would like to do it through jQuery.
我不想更改标记或CSS,但想通过jQuery进行更改。
We can use math for that :) 我们可以为此使用数学:)
$('li').on('click', function () {
$(this).animate({
opacity: (0.5 / $(this).css("opacity"))
}, 500, function () {
$(this).toggleClass('completed');
});
});
You can do it like following. 您可以按照以下步骤进行操作。
$('li').on('click', function () { if ($(this).is(':animated')) return; //ignore click while animating var opacity = $(this).css('opacity') == 1 ? 0.5 : 1; $(this).animate({ opacity: opacity }, 500, function () { $(this).toggleClass('completed'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Click Here</li> <li>Click Here</li> </ul>
All you need is a flag 您只需要一个标志
$('li').on('click', function () {
var opacity,
flag = $(this).data('flag');
if ( flag ) {
opacity = 1;
} else {
opacity = 0.5;
}
$(this).animate({
opacity: opacity
}, 500, function () {
$(this).toggleClass('completed');
$(this).data('flag', !flag);
});
});
(Really verbose on purpose) (真的很冗长)
$('li').on('click', function () { var opacity, flag = $(this).data('flag'); if ( flag ) { opacity = 1; } else { opacity = 0.5; } $(this).animate({ opacity: opacity }, 500, function () { $(this).toggleClass('completed'); $(this).data('flag', !flag); }); });
li {color : red; cursor: pointer; margin: 20px 0 0 0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> </ul>
The less verbose version 不太详细的版本
$('li').on('click', function () {
var flag = $(this).data('flag');
$(this).fadeTo(500, flag ? 1 : 0.5, function() {
$(this).toggleClass('completed').data('flag', !flag);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.