简体   繁体   中英

Dynamically set element height and width

I'm using Backbone to render a square tile element in which I set the height and then dynamically set the width to match the height. However, when trying to fetch the elements height, I get 0 returned.

Here is my code:

var app = app || {};

app.ClassModelView = Backbone.View.extend({
    className: 'tile',

    template: _.template('<%= name %>'),

    render: function() {
        var dim = 'calc(' + parseInt(100 / app.global.rows) + '% - ' + app.global.margin * (app.global.rows + 1) + 'px)'; //e.g. "30% - 20px"
        this.$el.append(this.template(this.model.attributes)).css({
            margin: app.global.margin + 'px',
            height: dim,
        }).css({
            width: this.$el.height() + 'px',
        });

        return this;
    }
})

How would I set the width of $el to the height? I'm not sure if I'm doing something syntactically wrong or if it is the way I'm using Backbone that is resulting in my problem.

I've ran into similar issues in the past. In most cases, it was because my view had rendered but had not yet been inserted into the DOM. This is pretty common when dealing with nested views.

You can test for this by setting a break point in your onRender method and checking this.$el.parent(). You might want to go up a few parents to make sure the parent elements are in the DOM.

You can get around this by binding to the DOMNodeInserted event:

this.$el.on('DOMNodeInserted', function(e) { console.log($(e.target).outerHeight()); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM