使用PHP和JavaScript的动态CSS

时间:2022-12-05 11:53:37

I want to set the window width (getting by JavaScript) in a PHP variable and use it to describe the attribute of the div container, but the following code doesn't work...

我想在PHP变量中设置窗口宽度(通过JavaScript获取)并使用它来描述div容器的属性,但以下代码不起作用...

<?php
header("Content-type: text/css; charset: UTF-8"); // Parsing CSS zu PHP
echo "<script type='text/javascript'>
    if(typeof(window.innerWidth) !== 'number') {
        if(document.documentElement.clientWidth !== 0) {
            width  = document.documentElement.clientWidth;
            height = document.documentElement.clientHeight; 
        }
        else {
            width  = document.body.clientWidth;
            height = document.body.clientHeight;
        }
    }else {
        width  = window.innerWidth;
        height = window.innerHeight;
    }
    $cwidth = document.write(width);
    </script>";
?>
@charset "UTF-8";
#container
{
    width: <?php echo $cwidth . 'px'; ?>; 
}

Greets

1 个解决方案

#1


0  

You can add this to the bottom of your HTML page and the width of #container gets set by JS when the page loads:

您可以将其添加到HTML页面的底部,并在页面加载时由JS设置#container的宽度:

<script type='text/javascript'>
if(typeof(window.innerWidth) !== 'number') {
    if(document.documentElement.clientWidth !== 0) {
        width  = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight; 
    }
    else {
        width  = document.body.clientWidth;
        height = document.body.clientHeight;
    }
}else {
    width  = window.innerWidth;
    height = window.innerHeight;
}
document.getElementById('container').style.width = width;
</script>

btw: You wrote clinet instead of client in your JS.

顺便说一句:你在JS中编写了clinet而不是client。

#1


0  

You can add this to the bottom of your HTML page and the width of #container gets set by JS when the page loads:

您可以将其添加到HTML页面的底部,并在页面加载时由JS设置#container的宽度:

<script type='text/javascript'>
if(typeof(window.innerWidth) !== 'number') {
    if(document.documentElement.clientWidth !== 0) {
        width  = document.documentElement.clientWidth;
        height = document.documentElement.clientHeight; 
    }
    else {
        width  = document.body.clientWidth;
        height = document.body.clientHeight;
    }
}else {
    width  = window.innerWidth;
    height = window.innerHeight;
}
document.getElementById('container').style.width = width;
</script>

btw: You wrote clinet instead of client in your JS.

顺便说一句:你在JS中编写了clinet而不是client。