这个。$ el.width()返回0?

时间:2013-12-29 23:15:52

标签: javascript jquery backbone.js width zepto

我正试图获得Backbone View的尺寸,几乎没有运气。这是因为它是异步的并且尚未添加到DOM中吗?

var CardView = Backbone.View.extend({
    model: Card,
    tagName: 'div',
    className: 'card',
    events: function () {
        return (Modernizr.touch) ? {"touchstart": 'flip'} : {"mousedown": 'flip'};
    },
    initialize: function () {
        var faces = document.createElement('div');
        var front = document.createElement('div');
        var back = document.createElement('div');
        this.$faces = $('<div></div>')
            .addClass('faces')
            .append($('<figure></figure>').addClass('front'))
            .append($('<figure></figure>').addClass('back'))
        this.$el.append(this.$faces);
        this.model.on("change", this.render, this);
        // Trying to print the width of this view:
        console.log(this.$el.width());
        // => returns: 0;
    },
    flip: function () {
        this.model.flip();
    },
    render: function () {
        if (this.model.get("flipped")) {
            this.$faces.addClass("flipped");
        }
        else {
            this.$faces.removeClass("flipped");
        }
        this.$faces.find('.back').addClass(this.model.get('pattern'));
    }
});

如果是这样,那么在集合视图中我肯定能够访问渲染的子视图,如下所示:

var CardGridView = Backbone.View.extend({
    className: 'card-grid',
    defaults: {
        columns: 4
    },
    render: function () {
        this.collection.forEach(this.addCard, this);
    },
    addCard: function (card) {
        var cardView = new CardView({model: card});
        cardView.render();
        $(cardView.el).css({'left':this.collection.indexOf(card)*110+'px'});
        this.$el.append(cardView.el);
        // Trying to print the width of this view:
        console.log($(cardView.el).width());
        // => returns: 0;
    }
});

1 个答案:

答案 0 :(得分:1)

除非您明确设置,否则宽度和高度为零。将元素插入文档时,将计算尺寸

var div = document.createElement('div');
var text = document.createTextNode('Hello, world!');
div.appendChild(text);
/*
div.style.width = '100px';
div.style.height = '100px';
*/
console.log('before width=' + div.style.width + ';' + div.clientWidth);
document.body.appendChild(div);
console.log('after width=' + div.style.width + ';' + div.clientWidth);

请参阅JSFiddle进行播放。