如果window.location.href.indexOf('player=1')添加样式

if window.location.href.indexOf('player=1') add style

本文关键字:添加 样式 player window indexOf location 如果 href      更新时间:2023-09-26

如果我的网站url=http://example.com/?player=1然后我找到了那个代码,但我不能使用它如果url=http://example.com/?player=1车身样式将是

body{ background:#000; }
<script type='text/javascript'>
  //<![CDATA[
  var curl = window.location.href;
  if (curl.indexOf('player=1') != -1) {
    curl = curl.replace('player=1', 'm=0');
    window.location.href = curl;
  }
  //]]>
</script>

它将player=1替换为m=0,但我需要使用它来添加样式

将其添加到您的脚本中

if(window.location.href.indexOf("example.com/?player=1") > -1){
  $('body').css("background-color","#000");
}

操作您自己的代码如下所示。

 var curl = window.location.href;
  if (curl.indexOf('player=1') != -1) {
   $('body').css("background-color","#000");
  }

如果要检查的字符串存在于URL中,则需要设置body元素的style

if(window.location.href.indexOf("player=1")!=-1)
    document.body.style.backgroundColor="#000";

或者,为了避免设置内联样式,如果要检查的字符串存在,则可以创建一个新类并将其应用于正文。

body.player1{
    background:#000;
}
if(window.location.href.indexOf("player=1")!=-1)
    document.body.classList.add("player1");

开始:

<script type='text/javascript'>
   //<![CDATA[
       var curl = window.location.href;
       if (curl.indexOf('player=1') != -1) {
           document.body.style.backgroundColor = "red"
       }
   //]]>
</script>

您可以利用JS的正则表达式。

实时演示

这是代码(HTML)-

<p>compu lack, Your styling is based on URL string</p>

CSS-

.dynamic-css {
   display: inline-block;
  background: tomato;
  color: #fff;
  padding: 5px;
  border-radius: 4px;
}

JS-

$(document).ready(function() {
  var url = /jsbin/.test(window.location.href);
  if (url) {
    console.log("Found 'StackOverflow in URL. I will add Style to text now.'")
    $('p').addClass('dynamic-css');
  }
});