【问题标题】:Why the setting of a margin results in two different values on desktop and mobile?为什么设置边距会在桌面和移动设备上产生两个不同的值?
【发布时间】:2019-06-11 03:10:48
【问题描述】:

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

我的代码

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

桌面上的结果边距(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

我在这里错过了什么?

【问题讨论】:

    标签: javascript jquery css window


    【解决方案1】:

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

    试一试:

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

    应该可以的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-04
      • 2021-06-03
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多