getting percent CSS position with jQuery

后端 未结 7 843
终归单人心
终归单人心 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:12

    You can try this. You can change the "element" and "parent" to be compatible with your project.

    var parent_height = $(element).parent().height(); // Height of parent. If you do something related to "width", get parent's width.
    
    var top_val_px   = $(element).css('top');
    var top_val_only = top_val_px.slice(0,-2); // Remove "px" part
    var top_Percentage = (top_val_only/parent_height) * 100; // Percentage will be a close value.
    

    I used a similar code and it worked.

提交回复
热议问题