可能重複:
Avoiding repeated constants in CSS解析JavaScript變量的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。
JavaScript中的CSS是計算後進行解析。您需要使用元素的javascript樣式屬性來完成此操作。 – 2011-03-24 20:05:57
我很抱歉把它分解給你,但你沒有CSS變量。 – harpo 2011-03-24 21:05:33