jquery扩展崩溃效率

时间:2012-09-10 16:00:23

标签: javascript jquery user-interface performance

我刚刚在我们网站的一部分上实施了一个简单的扩展/折叠系统。我尝试了几个现有的解决方案,但只是觉得太多努力使网站适应它,所以我写了自己的适合。

代码如下:

function hide(boxtohide, boxtomodify, expandbox) {

$('#' + boxtohide).hide(300);
$('#' + boxtomodify).css('background-image', 'url("images/new/date.png")');
$('#' + boxtomodify).css('height', '69px');
$('#' + expandbox).show(300);

}

function show(boxtohide, boxtomodify, expandbox, origheight, origurl) {
$('#' + expandbox).hide(300);
$('#' + boxtomodify).css('height', origheight);
$('#' + boxtomodify).css('background-image', 'url("'+origurl+'")');
$('#' + boxtohide).show(300);


}

背后的逻辑是:

  • 用户点击隐藏
  • 隐藏内容
  • 内容包装器替换为更薄的div
  • 展开内容包装器中显示的按钮(即它替换原始内容)

反过来再次扩张。

对我而言,代码感觉有点笨重,我不是一个javascript高手,所以也许有点深度在这里,欢迎任何建议!

戴夫

3 个答案:

答案 0 :(得分:1)

我建议的唯一明显的变化是$('#' + boxtomodify')行,可以压缩为:

function hide(boxtohide, boxtomodify, expandbox) {
    $('#' + boxtohide).hide(300);
    $('#' + boxtomodify).css({
        'background-image' : 'url("images/new/date.png")'),
        'height' : '69px' });
    $('#' + expandbox).show(300);
}

function show(boxtohide, boxtomodify, expandbox, origheight, origurl) {
    $('#' + expandbox).hide(300);
    $('#' + boxtomodify).css({
        'height' : origheight
        'background-image' : 'url("'+origurl+'")' });
    $('#' + boxtohide).show(300);
}

答案 1 :(得分:1)

你可以加速代码,只需将每个元素放在JS中,然后将这些CSS修改链接起来,如下所示:

function hide(boxtohide, boxtomodify, expandbox) {

var hideElem = document.getElementById(boxtohide),
    modElem = document.getElementById(boxtomodify),
    expandElem = document.getElementById(expandbox),
    cssObj = { 'background-image' : 'url("images/new/date.png")',
               'height' : '69px' };

$(hideElem).hide(300);
$(modElem).css(cssObj);
$(expandElem).show(300);

}

答案 2 :(得分:1)

我打赌你接近这种方式过于复杂,使用jQuery你可以用最少的代码做这些事情,例如:

jsfiddle

$('.toggle').on('click', 'h3', function() {
    var $content = $(this).next('.content');
    $content.slideToggle('fast');
});
相关问题