我问这个问题是为了回答这个问题,因为关于这个问题没有明确的信息或问题。我在评论中找到了解决方案,而不是在回答中。所以我希望这能对别人有所帮助。
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";
}
}
use href="javascript:void(0)"在标签中。javascript:void(0)可以在我们不希望在点击超链接时刷新或加载新页面的情况下使用。
1-如果您使用<a>
作为按钮,它将刷新页面,只要它有href=""
。因此,删除href
,它将工作,而无需刷新页面。
2-如果您想保留href
,那么将<a>
更改为button
。