How to get margin value of a div in plain JavaScript?

后端 未结 3 810
死守一世寂寞
死守一世寂寞 2020-12-24 02:06

I can get height in jQuery with

$(item).outerHeight(true);

but how do I with JS?

I can get the height of the li with



        
3条回答
  •  半阙折子戏
    2020-12-24 02:32

    Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.

    Object.defineProperty(Element.prototype, 'outerHeight', {
        'get': function(){
            var height = this.clientHeight;
            var computedStyle = window.getComputedStyle(this); 
            height += parseInt(computedStyle.marginTop, 10);
            height += parseInt(computedStyle.marginBottom, 10);
            height += parseInt(computedStyle.borderTopWidth, 10);
            height += parseInt(computedStyle.borderBottomWidth, 10);
            return height;
        }
    });
    

    This piece of code allow you to do something like this:

    document.getElementById('foo').outerHeight
    

    According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).

提交回复
热议问题