[英]How to change CSS when you find a special parameter in url by javascript
當我在 URL ?lname=lname
有以下搜索參數時,我想應用以下 CSS:
.fname {
display: none;
}
.lname {
display: block;
}
<div class="fname">
<input id="userInput" class="form-control" placeholder="Enter Your Name">
</div>
<div class="lname">
<input id="userInput" class="form-control" placeholder="Enter Your Name">
</div>
當前的 CSS 代碼如下所示:
.lname {
display: none;
}
您可以使用 URLSearchParams 從 URL 中獲取參數,然后根據您的參數添加 CSS 代碼
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)
更喜歡使用 JQuery 。
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
對於 Url 解析,請參閱此作為參考
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
使用此方法檢索參數
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])
}
}
};
然后使用簡單的檢查並使用 JQuery 應用 css
if(getUrlParameter("lname") === 'lname'){
$(".fname").css({display:'none'});
$(".lname").css({display:'block'});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.