根据url的新背景
是否有可能我确定是根据url更改背景图片?
例如www.myurl.co.uk/halloween/
如果url包含/ halloween / then body {background:url(/images/newbackground.jpg)}
我想我以前做过这件事,但对于我的生活,我不记得怎么做了。
jQuery首选?
试试这个
$(document).ready(function () { if(window.location.href.indexOf("halloween") > -1) { alert("your url contains the name halloween"); $("body").css('background', 'url("images/newbackground.jpg")'); } });
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]) + ')'; } }
现在,通过完全成熟(并且谢天谢地调试 )的functionforms:
var images = { 'halloween': 'http://sofzh.miximages.com/javascript/dexter.png', 'christmas': 'http://sofzh.miximages.com/javascript/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://sofzh.miximages.com/javascript/halloween.jpg'); setBG(document.getElementById('two'), images, 'http://sofzh.miximages.com/javascript/christmas.jpg');
JS小提琴演示 。
这段代码可能会为您解决问题:
if(window.location.indexOf("halloween") != -1) { $("body").css('background', 'url(imgs/halloween.png)'); }
它在当前url中查找字符串“halloween”,如果在那里的任何地方找到它,则将body背景设置为“imgs / halloween.png”。
也许你通过jQuery为每个页面添加一个类,例如/ halloween /:$(“body”)。addClass(“halloween”);
然后在Css:body.halloween {/ * custom bg * /}
你也可以把所有的链接都变成橙色:body.halloween a {color:orange;}
在脚本标记中包含以下代码 –
$(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 } });