jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。鼠标悬停(Hover)事件是 jQuery 中的一个常见事件,用于检测鼠标指针进入和离开元素的事件。
mouseenter
mouseleave
鼠标悬停图片通常用于实现图片的动态效果,例如改变图片的透明度、显示提示信息或切换图片等。
以下是一个简单的示例,展示如何使用 jQuery 实现鼠标悬停时改变图片透明度的效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Hover Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.hover-image {
opacity: 1;
transition: opacity 0.5s ease;
}
.hover-image:hover {
opacity: 0.5;
}
</style>
</head>
<body>
<img src="image.jpg" alt="Hover Image" class="hover-image">
<script>
$(document).ready(function() {
$('.hover-image').mouseenter(function() {
$(this).css('opacity', '0.5');
}).mouseleave(function() {
$(this).css('opacity', '1');
});
});
</script>
</body>
</html>
原因:
解决方法:
$(document).ready()
中,确保 DOM 元素加载完成后再绑定事件。$(document).ready(function() {
$('.hover-image').mouseenter(function() {
$(this).css('opacity', '0.5');
}).mouseleave(function() {
$(this).css('opacity', '1');
});
});
原因:
解决方法:
transition
属性。.hover-image {
opacity: 1;
transition: opacity 0.5s ease;
}
.hover-image:hover {
opacity: 0.5;
}
通过以上方法,可以有效解决鼠标悬停图片时遇到的常见问题。
图片 当我们在浏览网页的时候,描述性的文本通常不会跟在图片之后,而是当我们将鼠标移至图片上时,才会将文本显示出来,这样的好处是,以突显图片为主,并节省布局空间 HTML 结构如下
领取专属 10元无门槛券
手把手带您无忧上云