我有以下用于向下滑动隐藏内容区域的代码。它有效,但我怀疑它太笨拙并且可能会引发太多请求或事件。有人可以建议一种更有效地组合这些功能的方法吗?
$(".toggler").click(function (event){
event.stopPropagation();
$("#mobile-top").animate({'height':'toggle'}, 250);
});
$("#mobile-top").click(function(event){
event.stopPropagation();
});
$('.toggler').toggle(function() {
$(this).html('Close This Box <em class="fa fa-chevron-up"></em>');
}, function() {
$(this).html('Connect With Us! <em class="fa fa-chevron-down"></em>');
});
$('html').click(function(){
$("#mobile-top").slideUp();
$(".toggler").html('Connect With Us! <em class="fa fa-chevron-down"></em>');
});
最佳答案
我认为可以通过使用变量来改进代码,特别是在多次使用某个选择器时。 并尝试使用 ID 而不是类。
编辑
这是有效的代码,当您单击 HTML 区域外部时不会感到困惑。 (请注意,命名变量时不能包含 - 字符,就像我之前放置的那样)
$(document).ready(function(){
var toggler = $("#toggler");
var mobileTop = $("#mobile-top");
//top drop-down content animation
toggler.click(function(event){
event.stopPropagation();
mobileTop.slideToggle(250);
$(this).toggleClass('open');
$(this).html('Connect With Us! <em class="fa fa-chevron-down"></em>');
$(".open").html('Close This Box <em class="fa fa-chevron-up"></em>');
});
$('html').click(function(){
mobileTop.slideUp(250);
toggler.html('Connect With Us! <em class="fa fa-chevron-down"></em>');
toggler.removeClass('open');
});
$(mobileTop).click(function(event){
event.stopPropagation();
});
});
这也应该更有效。
值得一读: http://code.tutsplus.com/tutorials/10-ways-to-instantly-increase-your-jquery-performance--net-5551
关于javascript - 压缩/优化 jQuery 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110142/