如何使用 PHP 动态插入 CSS 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6187804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I dynamically insert a CSS class using PHP?
提问by Alexa Green
What's wrong with the following code? I would like to dynamically insert "current" CSS class when the respective <li>
element is clicked. Thanks!
以下代码有什么问题?我想在<li>
单击相应元素时动态插入“当前”CSS 类。谢谢!
<?php
$pg = $_SERVER['PHP_SELF'];
?>
<section>
<aside>
<nav>
<ul>
<li class="<?php if($pg == 'index.php?page=about.php'){echo 'current';} ?>"><a href="index.php?page=about.php">About</a></li>
<li class=""><a href="">Services</a></li>
</ul>
</nav>
</aside>
<section>
回答by hsz
Try with:
尝试:
<?php
$pg = $_GET['page'];
$allow = array('about.php', 'main.php', 'other.php');
if ( !in_array($pg, $allow) ) {
$pg = 'default_value';
}
?>
<section>
<aside>
<nav>
<ul>
<li class="<?php if($pg == 'about.php'){echo 'current';} ?>"><a href="index.php?page=about.php">About</a></li>
<li class=""><a href="">Services</a></li>
</ul>
</nav>
</aside>
<section>
回答by Tim Baas
<li class="<?php echo ($_GET['page'] == 'about.php')? 'current' : 'normal'; ?>">
<a href="index.php?page=about.php">About</a>
</li>
回答by MeLight
$_SERVER['PHP_SELF']
doesn't return the $_GET vars (?page=about.php
)
$_SERVER['PHP_SELF']
不返回 $_GET vars ( ?page=about.php
)
回答by Quentin
$_SERVER['PHP_SELF']
will start with /
and will not include the query string.
$_SERVER['PHP_SELF']
将以/
查询字符串开头且不包含查询字符串。
You should probably check $_GET['page']
instead.
你应该检查一下$_GET['page']
。
回答by locrizak
Well if your looking for clicked at runtime you need javascript not php. Something like this using jQuery will work for you:
好吧,如果您在运行时查找单击,则需要 javascript 而不是 php。像这样使用 jQuery 的东西对你有用:
$(document).ready(function(){
$('nav >ul li').click(function(){
//remove all current classes
$('.current').removeClass('current');
$(this).addClass('current');
});
});