开发者

Parse Javascript variable to CSS variables [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Avoiding repeated constants in CSS

I have a javascript file that I am using to obtain the width and height of the viewport to adjust my site's resolution. I can开发者_Python百科 get these values with javascript, but I don't really know where to go from here. I'd like to send the values to my CSS variables but I have not found a way to do this quickly. Is it possible? Here is my JS code:

<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>

For the CSS I was hoping to get away with something quick and easy but its not working:

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

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

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

I am assuming that I have the incorrect syntax within the variable declarations. I wrote it that way to show that I am trying to get the variable value from JS and pass it to CSS.


I think you're looking for something similar to this:

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


You want to add the css dynamically with the javascript, each element has its style and corresponding elements relating to css, use javascript to manipulate these

myHtmlElement.style.backgroundColor='green';

something along those lines should be fine.


As others mentioned, you can use individual elements' style property. If you want generic rules like .myClass { width: myVar }, you're gonna have to produce the whole CSS rule at runtime:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜