简体   繁体   中英

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:

.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:

.lname {
  display: none;
}

You can use URLSearchParams to get parameters from URL, and then add CSS code according to your parameters

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 .

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

For Url parsing see this as a reference

// 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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