根据到达的URL更改背景

时间:2016-08-25 17:26:35

标签: html css background

嗨,希望有人能提供帮助。

我有一个实时网站,也有一个开发网站,我在部署之前测试新代码,但基本上它们具有相同的内容,例如

  • 直播= www.myserver.com/live/index.html
  • 发展= www.myserver.com/development/index.html

有没有办法设置(比方说)CSS背景属性取决于用于到达网站的网址。

我当前的CSS =

body {
    background: #eff;
    /* change this to background: #ccc; if on development site */
    margin:25px;
}

为什么呢? 好吧,我经常发现自己在错误的网站上上传或测试新代码。

我知道这不是一个大问题,但如果我能够直观了解我正在测试哪个网站,那么这个问题很有用。

感谢您的关注。

现已解决感谢@Adam Buchanan Smith,@ Dekel和Green先生的投入。 我有点使用@ Dekel的逻辑,但是按照以下几行将其改为jQuery:

<script>
$(document).ready(function(){
// Set background dependent upon url i.e. www.myserver.com/cab or www.myserver.com/cab2
// cab2 is the development site, cab the live site
// Also change text in div id="live" from 'Live Site' to 'Development Site' if arrives at by cab2   
    if (document.location.pathname.indexOf('cab2') > -1){
    $('body').css({"background":"#BFFFDF"});
    document.getElementById('live').innerHTML = "Development Site";
    } else {
        $('body').css({"background":"#efffff"});
        document.getElementById('live').innerHTML = "Live Site";
    }
}
</script>

感谢所有人的兴趣!

2 个答案:

答案 0 :(得分:1)

不是你可以在纯html / css中做的事情,但你可以使用javascript和服务器端语言。

在javascript中,您可以检查document.location.hostnamedocument.location.pathname是否检查您当前正在使用的域名/网址。

在javascript中您可以使用:

if (document.location.pathname.indexOf('development') > -1) {
    body = document.getElementsByTagName('body')[0]
    body.setAttribute('class', body.getAttribute('class') + ' development')
}

使用PHP,您可以使用$_SERVER['REMOTE_HOST']$_SERVER['REQUEST_URI']

if (strpos($_SERVER['REQUEST_URI'], 'development')) {
    echo "<body class=\"development\">";
} else {
    echo "<body>";
}

css文件中,您可以使用:

body {
    background: #eff;
}
body.development {
    background: #ccc;
}

答案 1 :(得分:1)

理论上这样的事情可以使用document.referrer;

在纯粹的javascript中为你工作
<body onload="checkURL()">
</body>
<script>
function checkURL(){
var testPage = "www.testpage.com";
var livePage = "www.livepage.com";
var lastPage = document.referrer;

if (lastPage == livePage){
//do something here
}
else if {lastPage == testPage}
//do something else
}
else{
//umm what did you do?
}
</script>
相关问题