简体   繁体   English

当您通过 javascript 在 url 中找到特殊参数时如何更改 CSS

[英]How to change CSS when you find a special parameter in url by javascript

When I have the following search parameter in the URL ?lname=lname , I want to apply the following CSS:当我在 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>

The current CSS code looks like this:当前的 CSS 代码如下所示:

.lname {
  display: none;
}

You can use URLSearchParams to get parameters from URL, and then add CSS code according to your parameters您可以使用 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)

Prefer using JQuery .更喜欢使用 JQuery 。

<head>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>

For Url parsing see this as a reference对于 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  

Use this method to retrieve the parameters使用此方法检索参数

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

Then use a simple check and apply css using JQuery然后使用简单的检查并使用 JQuery 应用 css

if(getUrlParameter("lname") === 'lname'){
       $(".fname").css({display:'none'});
       $(".lname").css({display:'block'});     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM