左边的缩略图,默认加载150x150px的尺寸,
右图默认加载featured image原图
鼠标指上缩略图后,主图部分:
为减少CLS,缩略图强制设置尺寸为80x80
<img width="80" height="80" src="<?php echo the_post_thumbnail_url();?>" data-source="<?php echo the_post_thumbnail_url();?>" class='thumbnail-img'/> <?php $images = get_field('product_gallery'); if ($images) { foreach ($images as $image) { // 默认是加载原图,修改为加载缩略图,把原图url存在data-source中 //echo "<img src='".$image_src=$image['url']."' class='thumbnail-img' data-source=".$image['url']." />"; echo "<img width='80' height='80' src='".$image['sizes']['thumbnail'] ."' class='thumbnail-img' data-source=".$image['url']." />"; } }else{ echo "<style>#div_block-116-899{display:none;}</style>"; } ?>
.thumbnail-img{object-fit:cover;cursor:pointer;transition:0.3s;border-radius:6px;} .thumbnail-img:hover{opacity:0.6;border: 2px solid white;}
const mainImg = document.getElementById('main-img'); const thumbnails = document.getElementsByClassName('thumbnail-img'); // 共享的代码逻辑 function sharedLogic(thumbnailSrc) { // 创建一个新的 Image 对象 const newImg = new Image(); // 在图片加载完成后进行切换和淡入淡出效果 newImg.onload = function() { // 使用淡入淡出效果切换图片 mainImg.style.opacity = '0'; // 在图片完全淡出后切换图片路径 setTimeout(function() { // 切换图片路径 mainImg.src = thumbnailSrc; // 图片加载完成后再淡入显示 setTimeout(function() { mainImg.style.opacity = '1'; }, 200); }, 100); }; // 设置新的图片源 newImg.src = thumbnailSrc; } // 没有必要执行click,mouseenter已经包含了。 // click 事件处理程序 /* for (let i = 0; i < thumbnails.length; i++) { thumbnails[i].addEventListener('click', function() { const thumbnailSrc = thumbnails[i].src; sharedLogic(thumbnailSrc); }); } */ // hover(mouseenter)事件处理程序 for (let i = 0; i < thumbnails.length; i++) { thumbnails[i].addEventListener('mouseenter', function() { const thumbnailSrc = thumbnails[i].dataset.source; sharedLogic(thumbnailSrc); }); }
<img id="main-img" src="<?php echo the_post_thumbnail_url();?>" style="width:100%;object-fit:cover;width:100%;height:100%;max-width:500px;border-radius:6px"/>