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

时间:2016-05-11 10:09:08

标签: javascript jquery css

如果我的网站网址为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>

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

4 个答案:

答案 0 :(得分:3)

在脚本中添加

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");
  }

答案 1 :(得分:1)

如果要检查的字符串出现在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");

答案 2 :(得分:0)

你走了:

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

答案 3 :(得分:0)

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

Live Demo

这是代码(HTML) -

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

CSS -

$(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');
  }
});

JS

CardView