4

好的,所以我在php中做了一个样式切换器,我将它用作我网站上的隐藏功能,当用户键入“teema”时触发,页面内容顶部会出现一个模式框并显示可用的主题。

<ul>
    <li><a href="teema.php?teema=default" class="ajaxLink">Normaali</a></li>
    <li><a href="teema.php?teema=superhero" class="ajaxLink">Superhero</a></li>
    <li><a href="teema.php?teema=spacelab" class="ajaxLink">Spacelab</a></li>
    <li><a href="teema.php?teema=united" class="ajaxLink">United</a></li>
    <li><a href="teema.php?teema=cyborg" class="ajaxLink">Cyborg</a></li>
</ul>

但是,我想在不刷新页面的情况下更改主题,因此 css 应该在后台加载。这是 teema.php:

<?php
    $style = $_GET['teema'];
    setcookie("teema", $style, time()+604800);
    if(isset($_GET['js'])) {
        echo $style; 
    } 
    else{
    header("Location: ".$_SERVER['HTTP_REFERER']);  
    }
?>

以及检查 cookie 的索引上的 php:

<?php 
if(!empty($_COOKIE['teema'])) $style = $_COOKIE['teema'];
else $style = 'default';
?>
<link rel="stylesheet" href="css/<? echo $style;?>.css" id="theme">

如何在后台加载新的 css,并使用 jQuery 将其淡入旧 css?

4

3 回答 3

1

更改此链接的内容 ( $('$#theme').attr('href', 'css/' + selectedtheme +'.css');,您也可以在 javascript 中设置 cookie ( document.cookie = 'theme=' + selectedtheme)

于 2012-11-11T16:59:45.277 回答
1

您可以简单地发出 ajax 请求,以便返回 cookie

使用 jQuery:

$('.ajaxLink').click(function(e) {
    e.preventDefault();
    var teemaUrl=this.href;
    var teema=teemaUrl.split('=').pop()
    $.get(teemaUrl, { js:true}, function(data){
       $('#theme').attr('href','css/'+ teema+'.css')

    })
});

这将解析teema来自 link 的值href,调用它href(可能需要添加路径信息)并更新hrefID=theme 的链接标签

于 2012-11-11T17:02:44.347 回答
1

您可以在 PHP 文件中给出 JavaScript 内容类型的响应并操作样式表。

以这种方式更改代码:

<?php
    $style = $_GET['teema'];
    setcookie("teema", $style, time()+604800);
    if(isset($_GET['js'])) {
        // echo $style; 
    } 
    else{
     // header("Location: ".$_SERVER['HTTP_REFERER']);  
    }
    header("Content-type: text/javascript");
?>
document.getElementById("theme").setAttribute("href", "teema.css");

使用 AJAX 和 PHP 更改主题。

由于您已经id="theme"<link />标签中使用了,我们可以使用 AJAX 在 jQuery 中轻松设置内容。

因此,您以这种方式提出主题请求:

$.getScript("theme.php?teema=theme");

在 PHP 中:

header("Content-type: text/javascript");
$('#theme').attr('href', 'css/<?php echo $_GET['teema']; ?>');
于 2012-11-11T16:54:31.953 回答