使用 jQuery 获取百分比 CSS 位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5230425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getting percent CSS position with jQuery
提问by ran levi
I'm trying to get an element's CSS (top and left) with jQuery:
我正在尝试使用 jQuery 获取元素的 CSS(顶部和左侧):
$(element).css('top');
but instead of "12%" like it should be, I get the pixels.
How do I get the percent?
但不是像应该的“12%”,我得到了像素。
我如何获得百分比?
HTML:
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>
回答by Mauvis Ledford
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.)
没有 jQuery 并为您提供您创建的类型的实际值(百分比、ems 等)
回答by Thomas Menga
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.
关于您的先例评论,如果您想使用 css('top'),请不要忘记 parseInt 它。
回答by Joel Box
This is also an option:
这也是一种选择:
$(element)[0].style.top
回答by Jan Paepke
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.
有一种(非常简单的)方法可以做到这一点!
即使使用样式表。
关键是通过暂时隐藏父级来防止jquery计算值。
$(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.
BTW:别担心,隐藏和重新显示太快了,你的用户是看不到的。
回答by Maxim Manco
calculate it by your own:
自己计算:
($(element).css('top') / parentHeight) * 100;
回答by cchamberlain
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;
};