[英]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.