优化我的jQuery代码的编写方式

时间:2012-12-15 13:32:50

标签: javascript jquery optimization

我刚刚开始学习jQuery,我似乎能够按照我想要的方式工作,但我觉得我写它的方式效率不高。以下这个例子中是否有人可以帮助我:

$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});

    $(window).resize(function() {
        $('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
    });

所以我在这里将div放在屏幕中央。然后它也会在窗口调整大小时再次执行它,因为其内容宽度属性是百分比值。它完美无缺,但我不禁觉得必须有更好的方法来写这个。任何帮助将不胜感激。谢谢

4 个答案:

答案 0 :(得分:1)

您可以缓存对象并触发resize事件,这样就可以在DOM Ready上执行resize处理程序。

$(window).resize(function() {
    var $elem = $('.tiles-wrapper');
    $elem.css({
        top: '50%',
        left: '50%',
        margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
    });
}).resize()

答案 1 :(得分:0)

var $tilesWrapper = $('.tiles-wrapper');

function setWrapperStyle () {
  var halfWidth = $tilesWrapper.width() * 0.5;
  var halfHeight = $tilesWrapper.height() * 0.5;
  $tilesWrapper.css({
    top: '50%',
    left: '50%',
    margin: '-' + halfHeight + 'px 0 0 -' + halfWidth + 'px'
  });
}

setWrapperStyle();
$(window).on('resize', setWrapperStyle);

答案 2 :(得分:0)

你应该用你的第一行写一个函子:

function center(){
    $('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
}

然后你第一次调用它,当你调整窗口大小时调用它:

center();
$(window).resize(center);

答案 3 :(得分:0)

你真的需要jquery吗? 你可以直接使用css

.tiles-wrapper{
top:50% ;
left:50% ;
width: //what u given
height: //what u given
margin-left: //tiles width/2
margin-right: //tiles height/2
position: //absolute or float
}

如果要动态计算高度和宽度 只需在准备好的文件上写下这个

var $elem = $('.tiles-wrapper');
    $elem.css({
        top: '50%',
        left: '50%',
        margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
    });

在重新调整大小时,它将自动在中心位置。