【问题标题】:how to combine javascript variable to css如何将javascript变量组合到css
【发布时间】:2017-12-17 18:43:33
【问题描述】:

我想用科尔多瓦 jquery 制作简单的应用程序,我想根据手机/平板电脑的屏幕宽度生成 div 的宽度。 我用这个得到了屏幕的宽度

var physicalScreenWidth = window.screen.width * window.devicePixelRatio;
var physicalScreenHeight = window.screen.height * window.devicePixelRatio;

问题是如何将屏幕宽度与我的 css 结合起来。

这是我的静态 css,我不知道如何将可变宽度组合到这个 css。 我手动创建宽度:300px、130px 等。当手机/平板电脑不同英寸时会出现问题..

.some {
margin-left:-10px;
    width:300px;
    height:130px;
    margin-bottom: 5px;
    background-color:#fff;
    border-width:1px;
    border-style:solid;
    border-bottom-color:#aaa;
    border-right-color:#aaa;
    border-top-color:#ddd;
    border-left-color:#ddd;

}

.one{
  float:left;
  width:130px;
  height:130px;
}
.three{
    width:170px;
  height:130px;
    position:absolute;
    left:140px;

}

.four{
  width:170px;
  height:70px;
}
.five{
  width:170px;
  height:60px;
}

HTML

<div class="some">
    <div class="one"><img class="bgr" src="1.jpg"></div>

    <div class="three">
        <div class="four"><p style="margin-left:10px;margin-top:2px;"><font face="arial" size="3"><b>Descc ...</b></font></p></div>
        <div class="five"></div>
    </div>
</div>

结果

【问题讨论】:

  • 你不能用 % 代替 px 吗?
  • 我知道,% 是一个解决方案,但问题是 div ONE 中的图像。我想将图像的宽度和高度全部放入 div 之一(图像的宽度和高度 = div 的宽度和高度)任何解决方案?
  • 您不需要为该 div 指定特定的宽度或高度。 jsbin.com/yajepih/edit?html,css,output

标签: android jquery css cordova


【解决方案1】:

您不需要将宽度值传递给 css。相反,css 本身可以测量它所应用的屏幕。 Media queries 是您的答案。 @media screen and (min-width: 768px) and (max-width: 1024px) 用于平板电脑,@media screen and (max-width: 768px) 用于手机。

【讨论】:

  • 你怎么知道平板电脑的宽度是 768px-1024px?
  • 您可以为特定尺寸编写 css。但这个范围适用于市场上普通尺寸的平板电脑。小于 768 像素的屏幕可以容纳为手机编写的 css,大于 1024 像素的屏幕可以容纳为大型平板电脑/台式机编写的 css。
  • 好的..那么如何以最少的代码和最大的屏幕尺寸覆盖率来处理这种情况?
【解决方案2】:

jQuery

$(function(){
   var physicalScreenWidth = window.screen.width * window.devicePixelRatio;
   var physicalScreenHeight = window.screen.height * window.devicePixelRatio;
   $('.some').css({width:physicalScreenWidth });
})

CSS

.some{
   display:flex;
}
.one{
  flex:1;
}
.three{
  flex:1;
  display:flex;
  flex-direction:column;
 }

或者你可以使用媒体查询

@media screen and (max-width:600px){
   // write some css here
}

或使用 BootstrapSemanticBulma 等 css 框架

【讨论】:

  • 我肯定会选择仅使用 css 的解决方案,除非 OP 应该使用 javascript 有一些根本原因。此外,他应该避免将框架用于这种微不足道的事情。
【解决方案3】:

如果您可以使用简单的 jQuery,请使用:

$(".some").width(youtWidth);

编辑: 以同样的方式,您可以为您需要的每个元素设置宽度。查看以下代码,.some.one 元素的宽度设置为视图宽度的 33%。

var viewWidth = $(window).width();
$(".some").width(viewWidth * 0,33);
$(".one").width(viewWidth * 0,33);

【讨论】:

  • 不仅在 .some 中,而且在 div 1、3、4 和 5 中,我想根据智能手机的屏幕动态调整大小。示例:div 1 的宽度 = 手机屏幕宽度的 30%
猜你喜欢
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2021-11-20
  • 1970-01-01
  • 2015-01-17
  • 2021-07-27
  • 1970-01-01
相关资源
最近更新 更多