检测访问者是否在具有客户端脚本的索引页面上

是否可以通过客户端脚本检测访问者是否在索引页或域根目录中?

我认为javascript将是最好的方法,因为我想根据访问者是否在主页上附加值到图像文件。

非索引页面:

 

索引页面:

  

 var homeUrl = 'http://www.example.com'; if ( document.URL == homeUrl ){ // true }else{ // false } 

现在在HTML中的图像标记上添加一个id:

  

现在,您可以使用javascript轻松找到图像标记,并根据您在网站上的位置更改图像的来源。

 $(document).ready(function(){ var homeUrl = 'http://www.example.com'; var logotypeHome = 'https://stackoverflow.com/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更改徽标源时,图像上也可能有闪光。

另一种解决方案,没有基本URL。

 if ( window.location.pathname === '/' ){ //code for index page }else{ //other tasks }