如果找到类,如何处理隐藏元素 [英] How to approach hiding an element if class is found
问题描述
我一直在尝试找出jquery,并且在尝试中不仅试图找出如何使用各种东西,而且为什么,我还没有测试过任何东西,所以甚至不确定它是否有效(并道歉)如果我的代码糟糕/糟糕,请提前);但是,使用jquery似乎有无数种方法来处理所有问题,那么最好的方法是什么?如果未列出,有什么更好的方法?为什么?
I'm trying to figure out jquery still and in my attempts I'm trying to figure out not only how to use various thing but why, I haven't tested any of this so not even sure it works (and apologize ahead of time if my code is terrible/crap); however, with jquery it seems like there is an unlimited number of ways to approach everything, so what's the best method? what's a better method if not listed? Why?
如果存在.active
类,则此代码用于显示/隐藏元素.
This code is meant to show/hide an element if .active
class is present.
if($('.active').length > 0){
$('.more').attr('hidden').animate({opacity: "1"}, 200);
/* ...or should I use
$('.more').prop('hidden');
*/
}
或其他达到这种效果的东西?
or something to this effect?
if($('.active').length > 0){
$('.more).is(':hidden');
}
if($('.active').length === 0);
$('.more').not(':hidden');
}
还是只是添加/删除类更合适?
or is just adding/removing class more appropriate?
if($('.active').length > 0){
$('.more).addClass('hidden').fadeOut('fast');
}
if($('.active').length === 0);
$('.more').removeClass('hidden').fadeIn('fast');
}
还是应该像这样仅显示/隐藏项目?
or should item just be shown/hidden like this?
if($('.active').length > 0){
$('.more).hide('fast');
}
if($('.active').length === 0);
$('.more').show('fast');
}
说HTML是这样的:
<p class="more">More something or another</p> <!-- hidden if .active exists -->
<ul>
<li class="active"></li> <!-- active added dynamically if selected -->
<li></li>
</ul>
执行.active
切换的代码在工作中,并且在下面:
The code executing the .active
toggle is working and below:
$(document).ready(function() {
$('.vl-toggle-link').click(function(e) {
e.preventDefault();
$(this).siblings('.content').slideToggle(function(){
var offsetTop = $(this).parent().offset().top;
$('body,html').stop().animate({scrollTop: offsetTop-20 });
}).parent('li').toggleClass('active').siblings('li').removeClass('active').children('.content').slideUp();
});
)};
推荐答案
toggleClass
怎么样:
$('.more').toggleClass('hidden', !!$('.active').length))
然后通过CSS过渡添加动画:
Then add the animations via CSS transitions:
.more { -webkit-transition:opacity 500ms; opacity:1 }
.hidden { opacity:0 }
有很多做事"的方法,但是最后要写高性能,可理解的"代码并与浏览器支持保持一致等问题.jQueryAPI确实有一些很棒的方法,这些方法也可以自我实现.在命名约定中具有解释性.
There are many ways to "do things", but in the end it’s a matter of writing performant, "understandable" code and keeping in line with browser support etc. The jQuery API does have some great methods that are also self-explanatory in it‘s naming conventions.
使用类和CSS过渡,您可以很好地将逻辑与表示分离,并且其他同事很容易挂接到CSS,而不会受到内联样式的困扰.
Working with classes and CSS transitions allows you to separate logic from presentation nicely, and it’s easy for other co-workers to hook into the CSS without being bothered by inline styling.
这篇关于如果找到类,如何处理隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!