简体   繁体   中英

Why html will not keep css changes made by javascript when I click a button

I asked this question to answer it because there is no clear info or question about this. I found the solution in a comment, not in an answer. so I hope this will help others.

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <a href="" class="btn" id="btn" onclick="clickBtn()">btn</a>
  
  
  <div class="box" id="box"></div>
  
 
  
</body>
</html>

CSS

.btn{
  width: 150px;
  height: 50px;
  cursor: pointer;
  margin: 10px;
  background: black;
  color: white;
}

.box{
  width: 200px;
  height: 200px;
  background: orange;
  margin: 5px;
}

javascript

 var box = document.getElementById("box");

function clickBtn() {
   
  if (box.style.background = "orange"){ 
      box.style.background = "blue";
  } else {
      box.style.background = "green";
  }
}

1- If you use <a> as a button, it will refresh the page as long as it has href="" . so remove href and it will work without refreshing the page.

2- if you want to keep the href , then change the <a> to button . it worked for me.

use href="javascript:void(0)" in a tag. The javascript:void(0) can be used when we don't want to refresh or load a new page in the browser on clicking a hyperlink.

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