我有一组 div
,它们之间的垂直间距应为窗口的高度加上一个额外的空间 (+ 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
我在这里错过了什么?
最佳答案
嗯 - 这对我来说似乎很奇怪。我会在 .css()
之外的一个变量内创建偏移量,然后从 .css()
内部调用它。
试一试:
var add_margin = window.innerHeight + 100;
$(".text-container").css("margin", "50px auto "+add_margin+"px auto");
这应该有效。
当数字被解释为字符串而不是 float (或整数)时,我通常会做什么,尝试使用 parseInt()
或 parseFloat()
函数来告诉浏览器什么变量包含的数据类型。
关于javascript - 为什么边距的设置会在桌面和移动设备上产生两个不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56535965/