Pim*_*ger 117 javascript css jquery
在jQuery中,您可以将相对于父级的顶部位置作为数字,但如果设置了,则无法将css顶部值作为数字px.
说我有以下内容:
#elem{
position:relative;
top:10px;
}
Run Code Online (Sandbox Code Playgroud)
<div>
Bla text bla this takes op vertical space....
<div id='elem'>bla</div>
</div>
Run Code Online (Sandbox Code Playgroud)
$('#elem').position().top; //Returns the number (10+(the vertical space took by the text))
$('#elem').css('top'); //Returns the string '10px'
Run Code Online (Sandbox Code Playgroud)
但我希望将css top属性作为数字10.
如何实现这一目标?
M4N*_*M4N 205
您可以使用parseInt()函数将字符串转换为数字,例如:
parseInt($('#elem').css('top'));
Run Code Online (Sandbox Code Playgroud)
更新:(如Ben所建议的):你也应该给出基数:
parseInt($('#elem').css('top'), 10);
Run Code Online (Sandbox Code Playgroud)
强制将其解析为十进制数,否则以"0"开头的字符串可能会被解析为八进制数(可能取决于所使用的浏览器).
Iva*_*nos 25
一个基于M4N答案的jQuery插件
jQuery.fn.cssNumber = function(prop){
var v = parseInt(this.css(prop),10);
return isNaN(v) ? 0 : v;
};
Run Code Online (Sandbox Code Playgroud)
那么您只需使用此方法获取数字值
$("#logo").cssNumber("top")
Run Code Online (Sandbox Code Playgroud)
Gon*_*ing 13
基于Ivan Castellanos的答案(基于M4N的答案),这是一个稍微实用/高效的插件.使用|| 0将在没有测试步骤的情况下将Nan转换为0.
我还提供了float和int变体以适应预期用途:
jQuery.fn.cssInt = function (prop) {
return parseInt(this.css(prop), 10) || 0;
};
jQuery.fn.cssFloat = function (prop) {
return parseFloat(this.css(prop)) || 0;
};
Run Code Online (Sandbox Code Playgroud)
$('#elem').cssInt('top'); // e.g. returns 123 as an int
$('#elem').cssFloat('top'); // e.g. Returns 123.45 as a float
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104961 次 |
| 最近记录: |