getting percent CSS position with jQuery

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

    I had a need to calculate something similiar but in my case it was the left %, you can update the code below to use the window height if you are going for a vertical percentage value -

    getLeftPercent = function() {
        var leftStr = $('#my-obj').css('left'),
            pxPos = leftStr.indexOf('px'),
            leftVal = leftStr.substr(0, pxPos),
            leftPercent = (leftVal / $(window).width() * 100).toString(),
            dotPos = leftPercent.indexOf('.'),
            leftPercentStr = dotPos == -1 ? leftPercent + '%' : leftPercent.substr(0, dotPos) + '%';
        return leftPercentStr;
    };
    

提交回复
热议问题