适用于不同CSS样式的每个循环的PHP

时间:2014-06-18 12:49:08

标签: php for-loop

如果网址以某个结尾结束,我想将链接设为粗体:

http://url.com/test#style1

http://url.com/test#style2

......依此类推#style15

最好用PHP或Javascript做到这一点吗? 我可以将以下内容转换为贯穿#style1 - #style15?

的循环
<?php
$URL = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

if ($URL == "http://url.com/test#style1") { ?>

<style>.a1 {font-weight:bold;} </style>

<?
}
else if ($URL == "http://url.com/test#style2") { 
?>

<style>.a2 {font-weight:bold;} </style>

<?
}?>

3 个答案:

答案 0 :(得分:1)

你不能在php中访问哈希,就像这里&#34;#style1&#34;从URL,为此你必须javascript。

以下是Javascript中的解决方案:

<script>
if (window.location.hash) {
    var hash = window.location.hash.substring(1);
    if (hash.length != 0) { 
      for(i=1; i<=15; i++){
          if(("style"+i) == hash){
             /* Used jQuery here */
             $(".a"+i).css("font-weight", "bold");
          }
      }
    }
}
</script>

答案 1 :(得分:0)

PHP无法访问散列(#)后面的部分或URL,因此只能使用JavaScript。

您可以location.hash访问此部分网址。

答案 2 :(得分:0)

我建议您使用CSS来应用样式。它可以轻松读取属性的最终字符(E.G $ =),并在不使用PHP或Javascript的情况下应用适当的样式。

a[href$="1"] { font-weight:bold; }
相关问题