.css(‘width’) and .css(‘height’) versus .width() and .height()

前端 未结 10 996
旧时难觅i
旧时难觅i 2021-01-07 19:44

Guys I\'ve been asking around and nobody can really tell me the benefits of using .css(‘width’) and .css(‘height’) rather than .width()

10条回答
  •  忘掉有多难
    2021-01-07 20:18

    I have provided this answer because the question was asking about things you can do with css() and not width() and vice versa. There is an interesting case for page elements which are hidden.

    I had a situation recently where I needed to move some elements dynamically that were sometimes hidden, sometimes not when the page loaded. When the elements were not hidden, it was easy to just use the elements actual width to create the new DOM structure. But when the elements are hidden, using .width() returned 0, and rightly so. So I needed to add some CSS width info to the elements class and from that I was able to create a statement like

    var width = $('#element').width() == 0 ? parseInt($('#element').css('width')) : $('#element').width();
    

    This enabled me to ensure I was using the width when it was available, but also providing a fallback value for when the element was hidden.

    Hopefully this adds to the understanding of the difference between what you can do with these two methods.

提交回复
热议问题