Javascript 基于URL部分更改背景图像

Javascript 基于URL部分更改背景图像,javascript,jquery,css,Javascript,Jquery,Css,我正试图添加到我的网站的功能,其中的背景将根据使用样式表的URL的一部分而改变 例如: address/shop/index.php = background image 1 address/shop/index.php?cPath=22 = background image 2 address/shop/index.php?cPath=23 = background image 3 address/shop/index.php?cPath=24 = b

我正试图添加到我的网站的功能,其中的背景将根据使用样式表的URL的一部分而改变

例如:

address/shop/index.php             = background image 1
address/shop/index.php?cPath=22    = background image 2
address/shop/index.php?cPath=23    = background image 3
address/shop/index.php?cPath=24    = background image 4

有什么想法吗?我已经看过Javascript和jQuery,但不确定选择哪一种或如何操作。

在html页面的body标记内键入:

<body background="your file">

</body>


您可以在需要不同背景的每个页面上执行此操作,它将覆盖任何样式正文的CSS样式。看起来您正在使用PHP,因此您应该能够在不使用javascript的情况下执行此操作。您只需要使用PHP的服务器变量

差不多

 $cPath = $_GET['cPath']; //This allows access to the query part of the url
 if($cPath == 24){
     //set background url
 }

您始终可以让url的部分被标记包围,例如
因此,代码如下所示:

<a>your url link 
    <font class='background1'>part with background1</font>
    <font class='background2'>part with background2</font>
</a>

这可能是一种骇人的方式,但通过这种方式,您至少可以对“链接部分”进行分类。

如果您真的想在客户端执行此操作,我建议:

var pageBackground = {
    'default' : 'classOne',
    '22' : 'classTwo',
    '23' : 'classThree'
};

document.body.className = pageBackground[window.location.split('cPath=')[1] || 'default'];
再加上样式表:

body.classOne {
    background-image: url(path/to/defaultImage.png);
}
body.classTwo {
    background-image: url(path/to/imageTwo.png);
}
body.classThree {
    background-image: url(path/to/imageThree.png);
}

为生成的html更改
的类(或要更改其背景的任何元素)。有不同的背景,有不同的工作classes@zerkms它在我设计过的每个网站上都对我有用,并且消除了对php或jquery的需求,这对DOM来说非常重要……不要看到任何可怕的事情,你可以用叉子和手来喝汤——这会管用的,但是用勺子更方便。PS:澄清一下,不是我否决了你(尽管我同意这个答案是值得的:-)我认为只有一个文件
index.php
。您必须根据变量动态创建标记-这会让您找到其他答案…$cPath=$\u GET['cPath']//如果($cPath==23){}set background:url(WoodenPlank.jpg)}$cPath=$\u GET['cPath'],则允许访问url的查询部分//这允许访问url的查询部分,如果($cPath==23){$bg='background:#000 url(WoodenPlank.jpg);}只要JavaScript完整地到达客户端浏览器,那么它就应该正常工作,是的。
body.classOne {
    background-image: url(path/to/defaultImage.png);
}
body.classTwo {
    background-image: url(path/to/imageTwo.png);
}
body.classThree {
    background-image: url(path/to/imageThree.png);
}