在 jQuery 中,您可以获得相对于父级的顶部位置作为数字,但如果它在 px
中设置,则无法将 css 顶部值作为数字。
说我有以下内容:
#elem{
position:relative;
top:10px;
}
<div>
Bla text bla this takes op vertical space....
<div id='elem'>bla</div>
</div>
$('#elem').position().top; //Returns the number (10+(the vertical space took by the text))
$('#elem').css('top'); //Returns the string '10px'
但我想让 css top 属性作为数字 10
。
如何实现这一目标?
原文由 Pim Jager 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 parseInt() 函数将字符串转换为数字,例如:
更新:( 按照本的建议):你也应该给出基数:
强制将其解析为十进制数,否则以“0”开头的字符串可能会被解析为八进制数(可能取决于所使用的浏览器)。