Javascript jQuery - 如果元素有类这样做
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4565075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - If element has class do this
提问by Adrian Florescu
I need an jQuery script that will see if any element has an specific class and do an action like change position.
我需要一个 jQuery 脚本来查看是否有任何元素具有特定的类并执行诸如更改位置之类的操作。
This is the way, but I don`t think this will work.
这是方法,但我认为这行不通。
$("a.contact").toggle(function() {
$("#contact").animate({
right: '0'
}, 2000);
if ($("#about").hasClass("opened")) {
$("#about").animate({
right: -700 + "px"
}, 2000);
}
}, function() {
$("#contact").animate({
right: -700 + "px"
}, 2000);
});
回答by Ken Redler
First, you're missing some parentheses in your conditional:
首先,您在条件中缺少一些括号:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
但您也可以将其简化为:
$('#about.opened').animate(...);
If #aboutdoesn't have the openedclass, it won't animate.
如果#about没有这个opened类,它就不会动画。
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
如果问题出在动画本身,我们需要更多地了解您的元素定位(绝对?绝对在相对父级内?父级是否有布局?)

