jQuery-parseFloat在使用时返回不同的值

jQuery-parseFloat在使用时返回不同的值,jquery,parsing,alert,parsefloat,Jquery,Parsing,Alert,Parsefloat,在此代码中: $("div#info_holder").css("marginLeft", "100%"); alert(parseFloat($("#info_holder").css("marginLeft"))); alert(parseFloat(document.getElementById("info_holder").style.marginLeft)); 第一个警报返回1037.78,第二个警报返回100 为什么 这是因为jQuery版本以像素形式返回边距,而原生JS以百分比形

在此代码中:

$("div#info_holder").css("marginLeft", "100%");
alert(parseFloat($("#info_holder").css("marginLeft")));
alert(parseFloat(document.getElementById("info_holder").style.marginLeft));
第一个警报返回1037.78,第二个警报返回100


为什么

这是因为jQuery版本以像素形式返回边距,而原生JS以百分比形式返回值。看看这个提琴,它在运行parseFloat之前记录了这些值

$("div#info_holder").css("marginLeft", "100%");

console.log($("#info_holder").css("marginLeft"));
console.log(document.getElementById("info_holder").style.marginLeft);

$(“#info_holder”).css(“marginLeft”)
返回像素,而
document.getElementById(“info_holder”).style.marginLeft
以百分比形式读取它。

正确。更进一步,我假设jQuery正在查看
div
的长方体模型,并在幕后进行一些计算,因此为什么要获得
1037.78
的像素值。当使用本机JavaScript时,我假设它正在按设置拉取值,
100%
。您可以通过取出parseFloat并简单地显示警报值来测试这一点,但这将是我的建议。我明白了!我想我将只使用getElementById。非常感谢!:)不,这看起来很复杂。jQuery是用来缓解问题的,而不是让事情变得更糟。我将只使用getElementById。不过,非常感谢!:)@确切地说是user3130281,jQuery是javascript的包装器,所以将javascript与jQuery一起使用不需要担心,也不需要糟糕的实践。