How can I get the width of an element using AngularJS?

后端 未结 2 452
说谎
说谎 2021-02-02 10:03

I realise I can use jQuery to get the width of an element, but I\'m curious; is there a way to do so using AngularJS?

2条回答
  •  被撕碎了的回忆
    2021-02-02 10:32

    Native JS (#id):

    document.getElementById(id).clientWidth;
    

    Native JS (querySelector (class, id, css3 selector)):

    document.querySelectorAll(".class")[0].clientWidth;
    

    Plugging this into angular.element:

    angular.element(document.getElementById(id)).clientWidth;
    angular.element(document.querySelectorAll(".class")[0]).clientWidth;
    

    If you need to get non rounded numbers, use getBoundingClientRect.

    angular.element(document.getElementById(id)).getBoundingClientRect();
    

    Some resources on the subject:

    • http://msdn.microsoft.com/en-us/library/hh781509(VS.85).aspx
    • https://developer.mozilla.org/en-US/docs/Web/API/Element.clientWidth
    • https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

    If this floats your boat in terms of syntax and the no-need to plug jQuery into the mix, be wary of cross browser hell.

提交回复
热议问题