香草JavaScript(Vanilla JavaScript)指的是不依赖任何框架或库的原生JavaScript代码。悬停在元素上更改背景颜色是一个常见的交互效果,通常通过事件监听器来实现。
这种效果可以通过以下几种方式实现:
addEventListener
监听mouseover
和mouseout
事件。:hover
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hover Effect</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: #ccc;
}
</style>
</head>
<body>
<div class="box" id="myBox"></div>
<script>
document.getElementById('myBox').addEventListener('mouseover', function() {
this.style.backgroundColor = 'lightblue';
});
document.getElementById('myBox').addEventListener('mouseout', function() {
this.style.backgroundColor = '#ccc';
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hover Effect</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: #ccc;
}
.box:hover {
background-color: lightblue;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
原因:
解决方法:
原因:
解决方法:
DOMContentLoaded
事件。document.addEventListener('DOMContentLoaded', function() {
document.getElementById('myBox').addEventListener('mouseover', function() {
this.style.backgroundColor = 'lightblue';
});
document.getElementById('myBox').addEventListener('mouseout', function() {
this.style.backgroundColor = '#ccc';
});
});
通过以上方法,可以有效解决悬停效果不生效或背景颜色变化延迟的问题。
领取专属 10元无门槛券
手把手带您无忧上云