检测访问者是否在具有客户端脚本的索引页面上 [英] Detect if visitor is on index page with client side scripting
问题描述
是否可以使用客户端脚本检测访问者是否在索引页面或域根目录上?
Is it possible to detect if a visitor is on the index page or domain root with client side scripting?
我认为javascript将是最好的方法,因为我会喜欢根据访问者是否在主页上附加值到图像文件。
I figure javascript would be the best method as I would like to append a value to an image file based on wether a visitor is on the home page or not.
非索引页面:
<img src="/img/logo.png" />
索引页:
<img src="/img/logo-home.png" />
推荐答案
var homeUrl = 'http://www.example.com';
if ( document.URL == homeUrl ){
// true
}else{
// false
}
现在在HTML中的图片标记上添加一个ID:
Now put an id on your image tag in the HTML:
<img src="/img/logo-home.png" id="logotype" />
现在您可以使用javascript轻松找到图片代码,并根据您的位置更改图片来源在网站上。
Now you can easily find the image tag with javascript and change the source of the image depending on where you are on the site.
$(document).ready(function(){
var homeUrl = 'http://www.example.com';
var logotypeHome = '/img/logo-home.png';
var logotypeGeneral = '/img/logo-general.png';
if ( document.URL == homeUrl ){
$('#logotype').attr("src", logotypeHome);
}else{
$('#logotype').attr("src", logotypeGeneral);
}
});
我仍然强烈建议为这样的事情寻求服务器端解决方案。如果客户端未启用JavaScript,则无效。当javascript更改徽标源时,图像上也可能有闪光。
I would still strongly recommend to go for a server-side solution for a thing like this. If the client doesn't have JavaScript enabled this will not work. Also there could be a flash on the image when the javascript changes the logo source.
这篇关于检测访问者是否在具有客户端脚本的索引页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!