将Javascript变量解析为CSS变量 [英] Parse Javascript variable to CSS variables
问题描述
可能重复:
避免在CSS中重复常数
我使用获取视口的宽度和高度来调整我的网站的分辨率。我可以得到这些值与javascript,但我真的不知道从这里去哪里。我想发送的值到我的CSS变量,但我没有找到一个方法来做到这一点很快。可能吗?这是我的JS代码:
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 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>
对于CSS,我希望能快速,简单但不起作用的东西:
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);}
变量声明中的语法不正确。我写了这样的方式来表明,我试图从JS获取变量值,并将其传递给CSS。
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';
这篇关于将Javascript变量解析为CSS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!