【问题标题】:this.$el.width() returning 0?this.$el.width() 返回 0?
【发布时间】:2014-01-16 20:15:03
【问题描述】:

我正在尝试获得 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'));
    }
});

如果是这样,那么肯定在 Collection 视图中我应该能够像这样访问渲染的子视图:

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;
    }
});

【问题讨论】:

    标签: javascript jquery backbone.js width zepto


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2016-12-29
      • 2015-12-15
      • 2017-06-23
      • 2011-11-19
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多