首页 > 解决方案 > 为什么设置边距会在桌面和移动设备上产生两个不同的值?

问题描述

我有一组div's,它们之间的垂直间距应为窗口的高度加上一个额外的空格 ( + 100px)。但是,在 jQuery 中设置此边距时,移动浏览器和桌面浏览器的边距不同,将附加值+ 100视为字符串而不是数字。

我的代码

$(".text-container").css("margin", "50px auto " + (window.innerHeight + 100) + "px auto")

DESKTOP (Chrome)上的结果边距

alert((window.innerHeight + 100) + ", " + typeof (window.innerHeight + 100) + ", " + $(".text-container").css("margin")) 

--> 740, number, 50px 18px 740px

在MOBILE (Chrome 和三星互联网)上产生的利润

alert((window.innerHeight + 100) + ", " + typeof (window.innerHeight + 100) + ", " + $(".text-container").css("margin")) 

--> 874, number, 50px 20.6094px 740100px 20.5938px

我在这里想念什么?

标签: javascriptjquerycsswindow

解决方案


嗯 - 这对我来说似乎很奇怪。我会在.css()变量内部创建偏移量,然后从内部调用它.css()

搏一搏:

var add_margin = window.innerHeight + 100;
$(".text-container").css("margin", "50px auto "+add_margin+"px auto");

那应该行得通。

当数字被解释为字符串而不是浮点数(或整数)时,我通常会做什么,尝试使用parseInt()orparseFloat()函数来告诉浏览器变量包含什么类型的数据。


推荐阅读