javascript - 单击以轻松转换图像
问题描述
我有一个英雄形象,点击箭头按钮(上一个/下一个)会改变。这部分效果很好,但是变化很大。我正在尝试在每个图像之间添加一个轻松过渡,以便它们快速淡入或淡出。有没有一种简单的方法可以使用下面的 JS 来做到这一点?我是初学者。谢谢!
<script>
$( document ).ready(function() {
var images = [
"tophalf-b.jpg",
"tophalf-a.jpg",
];
var imageIndex = 0;
$("#previous").on("click", function(){
imageIndex = (imageIndex + images.length -1) % (images.length);
$("#image").attr('src', images[imageIndex]);
});
$("#next").on("click", function(){
imageIndex = (imageIndex+1) % (images.length);
$("#image").attr('src', images[imageIndex]);
});
$("#image").attr(images[0]);
});
</script>
解决方案
由于src
无法在单个 IMGElement 上转换更改,因此您需要预先创建所有图像。这也将防止在浏览器仍在加载下一个图像时看到闪烁的白色。
使用 GPU 加速 CSStransition
和 CSStransform
来为您的图像属性设置动画opacity
。
使用JS 来切换一个 CSS".is-active"
类,作为回报,你的图像会褪色:
jQuery(($) => {
const images = [
"https://placehold.it/150x150/0bf?text=One",
"https://placehold.it/300x150/bf0?text=Two",
"https://placehold.it/300x150/fb0?text=Three",
];
const $img = $(images.map((src) => $("<img>", {src: src})[0])); // Generate IMGs
const $gal = $("#images").append($img); // Append them to a parent
const tot = images.length;
const anim = () => $img.removeClass("is-active").eq(idx).addClass("is-active");
let idx = 0;
$("#prev").on("click", () => {
idx = (idx + tot - 1) % tot;
anim();
});
$("#next").on("click", () => {
idx = (idx + 1) % tot;
anim();
});
anim(); // Init Animate!
});
#images {
height: 150px;
position: relative;
}
#images img {
position: absolute;
width: 100%;
height: 100%;
object-fit: contain; /* Scale image to fit parent element */
pointer-events: none;
opacity: 0;
transition: opacity 0.4s; /* Use GPU accelerated properties */
}
#images img.is-active {
opacity: 1;
pointer-events: auto;
}
<div id="images"></div>
<button type="button" id="prev">←</button>
<button type="button" id="next">→</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
推荐阅读
- charts - 如何为 CategoryFilter 控件正确配置事件侦听器/处理程序?
- python - 使用 MySQL 管理 Web 应用程序的用户身份验证
- liquibase - Diff 未检测到索引存在
- python - Python selenium 未正确执行小书签
- php - FIFO用于线程之间的通信
- border - PhpSpreadSheet : 边框粗细
- flutter - 新的颤振包不起作用
- c# - 如何从数据库字段中获取布尔值?
- swift - 如何设置 NavigationView 默认值?
- python - 如何使用python在selenium中通过其id名称的一部分查找元素