jquery animate() 帮助
当用户打开和关闭图片时,我使用此代码来更改不透明度,不幸的是,当用户单击图像时,不透明度不会停留在 1。有人有答案吗?
$(document).ready(function(){
$('img#slide').animate({"opacity" : .7})
$('img#slide').hover(function(){
$(this).stop().animate({"opacity" : 1})
}, function(){
$(this).stop().animate({"opacity" : .7})
});
$('img#slide').click(function(){
$(this).animate({"opacity" : 1});
});
});
I'm using this code to change opacity when user is on and off a picture unfortunately when the user clicks the image the opacity does not stay at 1. Anyone has an answer ?
$(document).ready(function(){
$('img#slide').animate({"opacity" : .7})
$('img#slide').hover(function(){
$(this).stop().animate({"opacity" : 1})
}, function(){
$(this).stop().animate({"opacity" : .7})
});
$('img#slide').click(function(){
$(this).animate({"opacity" : 1});
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要以某种方式在用户单击时禁用
mouseleave
动画。常见的方法是添加一个类,并使用
mouseleave
检查该类是否存在。测试现场示例: http://jsfiddle.net/KnCmR/
< strong>编辑:
如果您希望第二次单击将行为恢复为原始状态,请使用
toggleClass()
而不是addClass()
:jQuery 文档:
.hasClass()
- http://api.jquery .com/hasClass.addClass()
- http://api.jquery.com/hasClass.addClass()
jquery.com/addClass.toggleClass()
- http://api .jquery.com/toggleClassYou need to somehow disable the
mouseleave
animation when the user clicks.A common approach is to add a class, and have the
mouseleave
check for the existence of the class.Test the live example: http://jsfiddle.net/KnCmR/
EDIT:
If you want a second click to revert the behavior back to the original, use
toggleClass()
instead ofaddClass()
:jQuery docs:
.hasClass()
- http://api.jquery.com/hasClass.addClass()
- http://api.jquery.com/addClass.toggleClass()
- http://api.jquery.com/toggleClass您只需要跟踪它是否被点击即可。您可以通过几种方法来实现这一点,但由于您只有一个要跟踪的元素,因此变量是最简单的方法。我还优化了您的代码以利用链接。我还更改了您的选择器以提高效率。
#slide
比img#slide
更好,因为id
应该是唯一的:You just need to track whether it has been clicked or not. You can do it a few ways, but since you only have one element you are tracking, a variable is the simplest way to do it. I also optimized your code to utilize chaining. I also changed your selector to be more efficient.
#slide
is better thanimg#slide
since anid
is supposed to be unique:该线程中的所有答案都很好,并且可行。但为此,这里有一种不同的方法。
根据您的代码和问题,您实际上正在做的是从元素中删除悬停行为。应该按如下方式完成:
可以重构以允许以新颖的方式切换行为:
注意:我还没有测试过这个(我正在工作),但你明白了。
All the answers in this thread are good, and would work. But for the sake of it here's a different approach.
Based on your code and your question, what you're actually doing is removing the hover behaviour from the element. Which should be done as below:
Which can be refactored to allow toggling of the behaviour in a novel way:
Note: I haven't tested this (I'm at work), but you get the idea.