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

前端 未结 10 994
旧时难觅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:08

    Since this was the first hit in google when I was trying to remember the difference between the two, I thought I'd give a little more explanation with an example.

    I have a div called myDiv like this:

    border:1px solid black;
    padding-right: 15px;
    padding-left:15px;
    margin-right:10px;
    margin-left:10px
    

    Console gives me this:

    $('#myDiv').css('width') = 1100px;
    $('#myDiv').width() = 1068;
    

    1100 includes the 15 pixels for the right padding, the 15 pixels for the left padding, 2 pixels for the border(1 for each side) but NOT the margins. At least for me in chrome. 1068+15+15+1+1 = 1100

    Yes, there is overhead for doing Number($('#myDiv').css('width').replace('px', '')) but you only have to do it once each time. And you do have to cast the result as a Number, assuming that you want Number($('#myDiv').css('width').replace('px', '')) + 99 to be 1199. Otherwise you get 110099 as the answer.

提交回复
热议问题