Javascript 如果window.location.href.indexOf(';player=1';)添加样式
如果我的网站url= 然后我找到了那个代码,但我不能使用它 如果url=body,则将使用Javascript 如果window.location.href.indexOf(';player=1';)添加样式,javascript,jquery,css,Javascript,Jquery,Css,如果我的网站url= 然后我找到了那个代码,但我不能使用它 如果url=body,则将使用 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');
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>
body{background:#000;}
//
它将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元素的
样式
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的regex
以下是代码(HTML)——
JS
“添加样式”是什么意思?你需要解释你想做什么,或者你的问题不清楚。你在说什么风格?我的意思是如果url风格是body{background;#000}你只想在body中添加风格,如果在带有javascript的URL中有m=0
,我使用blog,并且我需要它用于所有链接blog@compulack您必须确保在所有页面中运行上述脚本。为什么不能单独使用“player=1”呢?@Mike它也可以单独使用player=1
。我使用了它,但没有发生任何事情
<p>compu lack, Your styling is based on URL string</p>
.dynamic-css {
display: inline-block;
background: tomato;
color: #fff;
padding: 5px;
border-radius: 4px;
}
$(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');
}
});