在 jQuery 中,显示隐藏的元素并同时应用高亮效果是常见的 UI 交互需求。这通常用于吸引用户注意力到新出现的内容或重要信息。
show()
和 animate()
$("#element").show().animate({
backgroundColor: "#ffff99"
}, 1000).animate({
backgroundColor: "#ffffff"
}, 1000);
show()
和 jQuery UI 的 effect()
方法$("#element").show().effect("highlight", {color: "#ffff99"}, 2000);
$("#element").show().addClass("highlight");
对应的 CSS:
.highlight {
background-color: #ffff99;
transition: background-color 1s ease;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<style>
.box {
width: 200px;
height: 100px;
background-color: #f0f0f0;
margin: 20px;
display: none;
}
.highlight {
background-color: #ffff99;
transition: background-color 1s ease;
}
</style>
</head>
<body>
<button id="showBtn">显示并高亮</button>
<div id="content" class="box">这是要显示的内容</div>
<script>
$(document).ready(function() {
// 方法1: 使用animate
$("#showBtn").click(function() {
$("#content").show().animate({
backgroundColor: "#ffff99"
}, 500).animate({
backgroundColor: "#f0f0f0"
}, 500);
});
// 方法2: 使用jQuery UI effect (需要引入jQuery UI)
// $("#showBtn").click(function() {
// $("#content").show().effect("highlight", {color: "#ffff99"}, 1000);
// });
// 方法3: 使用CSS类
// $("#showBtn").click(function() {
// $("#content").show().addClass("highlight");
// setTimeout(function() {
// $("#content").removeClass("highlight");
// }, 1000);
// });
});
</script>
</body>
</html>
animate()
方法改变背景色需要 jQuery UI 或 color 插件支持effect("highlight")
是 jQuery UI 提供的特效,需要引入 jQuery UI 库以上方法都能实现显示元素并应用高亮效果,选择哪种方法取决于项目需求和已引入的库。
没有搜到相关的文章