在JavaScript中实现点击按钮切换箭头的功能,通常涉及到DOM操作和CSS样式的变化。以下是一个简单的示例,展示了如何实现这一功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Arrow</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="toggleButton">Toggle Arrow</button>
<div id="arrow" class="arrow-down"></div>
<script src="script.js"></script>
</body>
</html>
.arrow-down::before {
content: "▼";
}
.arrow-up::before {
content: "▲";
}
document.getElementById('toggleButton').addEventListener('click', function() {
var arrow = document.getElementById('arrow');
if (arrow.classList.contains('arrow-down')) {
arrow.classList.remove('arrow-down');
arrow.classList.add('arrow-up');
} else {
arrow.classList.remove('arrow-up');
arrow.classList.add('arrow-down');
}
});
<script>
标签放在正确的位置(通常建议放在</body>
标签前)。通过上述方法,可以有效实现点击按钮切换箭头的功能,并解决常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云