根据网址更改背景图片,我有可能确定吗?
例如www.myurl.co.uk/halloween /
如果网址包含/万圣节/ 然后 body {background:url(/images/newbackground.jpg)}
我想我以前做过这件事,但对于我的生活,我不记得怎么做了。
jQuery首选?
答案 0 :(得分:4)
$(document).ready(function () {
if(window.location.href.indexOf("halloween") > -1) {
alert("your url contains the name halloween");
$("body").css('background', 'url("images/newbackground.jpg")');
}
});
答案 1 :(得分:2)
这段代码可能会为您解决问题:
if(window.location.indexOf("halloween") != -1) {
$("body").css('background', 'url(imgs/halloween.png)');
}
它在当前网址中查找字符串“万圣节”,如果在那里的任何地方找到它,则正文背景设置为“imgs / halloween.png”。
答案 2 :(得分:2)
jQuery为此增加了不必要的开销。给出图像关键字的映射:
var images = {
'halloween' : '/images/newbackground.jpg',
'christmas' : '/images/xmasbackground.jpg'
};
你可以这样做:
var url = document.location.href,
elem = document.getElementById('elementThatYouWantToStyle');
for (var keyword in images){
if (images.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
elem.style.backgroundImage = 'url(' + encodeURI(images[keyword]) + ')';
}
}
现在,完全成熟(和thankfully debugged)功能形式:
var images = {
'halloween': 'http://davidrhysthomas.co.uk/img/dexter.png',
'christmas': 'http://davidrhysthomas.co.uk/img/mandark.png'
};
function setBG(el, map, url) {
if (!el || !map) {
return false;
}
else {
url = url || document.location.href;
/* means you can pass an element's `id` or a reference to the node itself */
el = el.nodeType == 1 ? el : document.getElementById(el);
for (var keyword in map) {
if (map.hasOwnProperty(keyword) && url.indexOf(keyword) !== -1) {
el.style.backgroundImage = 'url(' + map[keyword] + ')';
}
}
}
}
setBG('one', images, 'http://some.domain.com/with/halloween.jpg');
setBG(document.getElementById('two'), images, 'http://some.domain.com/with/christmas.jpg');
答案 3 :(得分:1)
试试这个
<script>
var currentUrl = document.URL;
if(currentUrl == 'www.myurl.co.uk/halloween/')
document.body.style.backgroundImage = 'url(/images/newbackground.jpg)';
</script>
答案 4 :(得分:0)
也许你通过jQuery为每个页面添加一个类,例如for / halloween /: $( “正文”)addClass( “万圣节”);
然后在Css中: body.halloween { / * custom bg * / }
您也可以将所有链接设为橙色: body.halloween a {color:orange;}
答案 5 :(得分:0)
在脚本代码中包含以下代码 -
$(document).ready(function() {
var path = window.location.href.split("/");
if (path.length > 2) {
if(a[2] == "halloween" ) {
$('body').css({background : 'url(/images/newbackground.jpg)' });
}
else if(a[2] == "something_else") {
$('body').css({background : 'url(/images/something_else.jpg)' });
}
//more else if for other images
}
});