getting percent CSS position with jQuery

后端 未结 7 841
终归单人心
终归单人心 2021-02-13 19:05

I\'m trying to get an element\'s CSS (top and left) with jQuery:

$(element).css(\'top\');

but instead of \"12%\" like it should be, I get the p

7条回答
  •  不知归路
    2021-02-13 19:15

    There is a (very easy) way to do this!
    Even when using stylesheets.
    The key is to prevent jquery from calculating the value by temporarily hiding the parent.

    $(element).parent().hide();
    var top = $(element).css("top");
    $(element).parent().show();
    console.log(top);
    

    voila!

    If you want just the number without the "%" use

    top = parseFloat(top);
    

    BTW: Don't worry, the hiding and reshowing is so quick, it won't be visible for your users.

提交回复
热议问题