[英]Add margin-left, script inside php
问题是。 我要插入左边距:20%; 当用户登录时显示为maincontent。
不,我在语法上没有问题,我可以在js中完成,但是我被告知要使用php。 因此,我还在CSS和我的身体中添加了一个类。
<?php
if ($_SESSION['username']){
include("/view/leftmenu.php");
}
?>
如何在php中激活CSS?
正如语法高亮显示的那样,您试图将单引号放在单引号字符串中。
您的选择是:
\\'
转义单引号。 ?> ... <?php
而不是echo
。 logged-in
一样向主体添加一个类,并像body.logged-in #maincontent { margin-left: 20%; }
这样拥有CSS规则body.logged-in #maincontent { margin-left: 20%; }
body.logged-in #maincontent { margin-left: 20%; }
? (对于您的JavaScript而言,这也是无效的;您需要引用20%
。百分比不是合法的JS。)
将JavaScript放在双引号中,并在其中加上单引号。 您可能还想先运行您的include
。 include
不需要()
。 您的代码可能更像:
<?php
session_start(); // has to be run before any headers are sent
if(isset($_SESSION['username'])){
include '/view/leftmenu.php';
echo "<script type='text/javascript'>$('#maincontent').css('margin-left', '20%');</script>";
}
?>
但是,更好的解决方案更像是:
<?php
session_start(); $marginLeft = '0'; // $marginLeft should be your default
if(isset($_SESSION['username'])){
$marginLeft = '20%';
include '/view/leftmenu.php';
}
echo "<!DOCTYPE html><html><head><style type='text/css'>".
"#maincontent{margin-left:$marginLeft;}</style></head><body>".
"<div id='maincontent'>content</div></body></html>";
?>
更好的方法如下:
<?php
session_start(); $className = 'withoutMargin'; // $marginLeft should be your default
if(isset($_SESSION['username'])){
$className = 'withMargin';
include '/view/leftmenu.php';
}
?>
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.withoutMargin{
margin-left:0;
}
.withMargin{
margin-left:20%;
}
</style>
</head>
<body>
<?php echo " <div class='$className'>"; ?>
<!-- your content here -->
</div>
</body>
</html>
注意:上面的代码不必看起来完全像这样。 这仅说明了概念。 您将进行更多的代码测试以设置提交等等。 另外,在第二个示例中,我建议使用外部CSS,因此它由用户的浏览器缓存。
20%需要用引号引起来:
$('#maincontent').css('margin-left', '20%');
这也适用于px,em,pt和任何其他形式的CSS度量单位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.