【问题标题】:Parse Javascript variable to CSS variables [duplicate]将Javascript变量解析为CSS变量[重复]
【发布时间】:2013-05-28 10:44:07
【问题描述】:

可能重复:
Avoiding repeated constants in CSS

我有一个 javascript 文件,我用它来获取视口的宽度和高度,以调整我网站的分辨率。我可以使用 javascript 获取这些值,但我真的不知道从哪里开始。我想将这些值发送到我的 CSS 变量,但我还没有找到快速完成此操作的方法。可能吗?这是我的 JS 代码:

<script type="text/javascript">
<!--

  var viewportwidth;
  var viewportheight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

  if (typeof window.innerWidth != 'undefined')
  {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
  }


 else if (typeof document.documentElement != 'undefined'
 && typeof document.documentElement.clientWidth !=
 'undefined' && document.documentElement.clientWidth != 0)
 {
   viewportwidth = document.documentElement.clientWidth,
   viewportheight = document.documentElement.clientHeight
 }


 else
 {
   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
   viewportheight = document.getElementsByTagName('body')[0].clientHeight
 }
   document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');
//-->
</script>

对于 CSS,我希望能够快速简单地摆脱它,但它不起作用:

@variables{
ViewWidth:'+viewportwidth+';}

@variables{
ViewHeight:'+viewportheight+';}  

html{
max-width: var(ViewWidth);
max-height: var(ViewHeight);}

我假设我在变量声明中的语法不正确。我这样写是为了表明我正在尝试从 JS 获取变量值并将其传递给 CSS。

【问题讨论】:

  • 在计算 css 后解析 JavaScript。您需要使用元素的 javascript 样式属性来执行此操作。
  • 很抱歉打扰您,但您没有 CSS 变量。

标签: javascript css


【解决方案1】:

我认为您正在寻找类似的东西:

var parentElement = document.documentElement || document.body;
parentElement.style.maxWidth = parentElement.clientWidth + 'px';
parentElement.style.maxHeight = parentElement.clientHeight + 'px';

【讨论】:

    【解决方案2】:

    你想用javascript动态添加css,每个元素都有自己的样式和css相关的对应元素,用javascript来操作这些

    myHtmlElement.style.backgroundColor='green';
    

    类似的东西应该没问题。

    【讨论】:

    • 在我的情况下,body.style.min-width ='+viewportwidth+'; 应该可以工作吗?
    • viewportwidth 需要是一个 javascript 变量,但是您可以像获取 min-width 一样轻松地获取 viewports width 属性,并使用该值进行设置。
    【解决方案3】:

    正如其他人提到的,您可以使用单个元素的 style 属性。如果你想要像 .myClass { width: myVar } 这样的通用规则,你必须在运行时生成整个 CSS 规则:

    https://developer.mozilla.org/en/DOM/stylesheet.insertRule

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      相关资源
      最近更新 更多