通过javascript在url中找到特殊参数时如何更改CSS
当我在URL通过javascript在url中找到特殊参数时如何更改CSS,javascript,html,css,Javascript,Html,Css,当我在URL?lname=lname中有以下搜索参数时,我希望应用以下CSS: .fname { display: none; } .lname { display: block; } 更喜欢使用JQuery <head> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> 使用此方法检索参数 var get
?lname=lname
中有以下搜索参数时,我希望应用以下CSS:
.fname {
display: none;
}
.lname {
display: block;
}
更喜欢使用JQuery
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
使用此方法检索参数
var getUrlParameter = function getUrlParameter(a) {
var d = window.location.search.substring(1),
c = d.split("&"),
e, b;
for (b = 0; b < c.length; b++) {
e = c[b].split("=");
if (e[0] === a) {
return e[1] === undefined ? true : decodeURIComponent(e[1])
}
}
};
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('lname');
if(myParam !== null){
var styles = `
.lname{ display: none; }
}
var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
您可以使用URLSearchParams从URL获取参数,然后根据您的参数添加CSS代码
var getUrlParameter = function getUrlParameter(a) {
var d = window.location.search.substring(1),
c = d.split("&"),
e, b;
for (b = 0; b < c.length; b++) {
e = c[b].split("=");
if (e[0] === a) {
return e[1] === undefined ? true : decodeURIComponent(e[1])
}
}
};
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('lname');
if(myParam !== null){
var styles = `
.lname{ display: none; }
}
var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
如果有一些服务器端逻辑,您可以根据查询字符串定义头中的css文件。然后,您不必等待jquery/js脚本加载并执行exexute,用户就可以看到正确的样式。
if(getUrlParameter("lname") === 'lname'){
$(".fname").css({display:'none'});
$(".lname").css({display:'block'});
}
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('lname');
if(myParam !== null){
var styles = `
.lname{ display: none; }
}
var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)