簡體   English   中英

javascript 將 class 添加到基於 url 的主體

[英]javascript to add class to body based on url

我有兩個域,並且都有相同的 web 頁面。 相同的 HTML CSS 和內容。 foo.com 和 bar.com

兩個網站都駐留在同一個主機中並返回相同的文件。 這樣我就不必在兩個域中復制更改。 我只編輯一個文件,兩個域都更新了。

現在我想在 foo.com 上更改一些 colors 並在 bar.com 上隱藏一些元素,但仍然不想復制該網站。

我想要一個 JavaScript 代碼片段,它可以檢測頁面的當前 URL 並將 class 添加到正文中。 如果有東西只能檢測到域,那就太好了。

嘗試在 javascript 中使用Window.location 添加一些自定義邏輯。

 // Get the current browser url. const url = window.location.href; console.log(url); // Selecting the body tag const body = document.getElementsByTagName("BODY")[0]; // Adding a custom check to check whether the url contains our domain. if (url.indexOf('stacksnippets') > -1) { body.className += ' class-one'; } else { body.className += ' class-two'; }
 .class-one { color: blue; }.class-two { color: green; }
 <body> <h2>JavaScript</h2> <h3>The window.location object</h3> </body>

嘗試這個..

 if(window.location.href == 'https://stacksnippets.net/js'){ $("#demo").addClass('demoClass'); }
 .demoClass{ color: green; background-color: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id="demo">Color changed as per url change</p>

在正文末尾的script中放入以下內容:

您也可以使用 jquery。 簡而言之,使用 documet/winod 加載事件來放置基於主機的邏輯。

window.addEventListener('load', function() {
  var isFoo = window.location.href.indexOf('foo.com') > -1;
  var body = document.getElementsByTagName("body")[0];
  var class = isFoo ? 'foo-class' : 'bar-class';
  body.className = body.className + ' '+ class;
  
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM