Get a number for a style value WITHOUT the “px;” suffix

前端 未结 4 612
梦毁少年i
梦毁少年i 2020-12-05 06:19

I am making a RTS game in Javascript and HTML. Sounds ambitious I know but I\'m not shooting for the stars here. Just a little something to keep me entertained.

I

4条回答
  •  情深已故
    2020-12-05 06:51

    An alternative approach to the one from Konsolenfreddy, is to use:

    var numericValue = window
        .getComputedStyle(document.getElementById('div'),null)
        .getPropertyValue('left')
        .match(/\d+/);
    

    JS Fiddle demo.

    The benefit of this approach is that it works to retrieve the value set in CSS, regardless of that value being set in the style attribute of the element or in a linked stylesheet, which I think Konsolenfreddy's approach is limited by.

    References:

    • window.getComputedStyle().
    • document.getElementById().
    • match().
    • CSSStyleDeclaration.getPropertyValue()
    • Regular Expressions.

提交回复
热议问题