简体   繁体   中英

getting percent CSS position with jQuery

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 pixels.
How do I get the percent?

HTML:

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<style type="text/css">
.parWrapper {
    position:absolute;
    top: 40%
}
</style>
</head>
<body>
<div> 
    <div id="crap" class="parWrapper" style="left:50%">
    Wrap1   
    </div>

    <div class="parWrapper">
    Wrap2
    </div>

    <div class="parWrapper">
    Wrap3   
    </div>

    <div class="parWrapper">
    Wrap4   
    </div>

    <div class="parWrapper">
    Wrap5   
    </div>

</div>

</body>

I just encountered this myself and thought it weird, too.

Instead of:

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

I just did:

 element.style.top

No jQuery and gives you the actual value in the type you made it (percent, ems, etc.)

You can do this:

$(element).position().top / $(element).parent().height() * 100

Regarding your precedent comment, if you want to work with css('top'), don't forget to parseInt it.

这也是一种选择:

$(element)[0].style.top

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.

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;
};

自己计算:

($(element).css('top') / parentHeight) * 100;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM