如何实现图片点击平滑缩放切换并通过scrollIntoView自动滚动居中
图片点击缩放切换功能修复方案
核心问题根因
- 过渡动画失效/卡顿:CSS
auto类型的宽高属性无法被transition插值过渡,jQuery animate也不支持none作为尺寸参数,所以会出现动画生硬、尺寸卡住的问题。图片恢复原始尺寸后没有做溢出处理,会导致页面滚动异常。 - scrollIntoView不生效:该方法是原生DOM API,不能直接在jQuery包装对象上调用;同时如果在缩放动画完成前触发,会按缩放前的元素位置计算偏移,导致定位错误。
完整可运行实现代码
<!DOCTYPE html> <html> <head> <script src="jquery.js"></script> <style> img { margin: 20px auto; display: block; padding: 2%; width: 90vw; box-sizing: border-box; object-fit: contain; transition: all 0.3s ease; cursor: zoom-in; } img.scaled { cursor: zoom-out; } </style> </head> <body> <img class="item" src="images/kitten1.png"> <img class="item" src="images/kitten2.png"> <img class="item" src="images/kitten3.png"> </body> <script> $(window).on('load', function() { // 预存所有图片的原始尺寸 $(".item").each(function() { $(this).data({ originW: this.naturalWidth, originH: this.naturalHeight }); }); $(".item").click(function() { const $currentImg = $(this); const isScaled = $currentImg.hasClass('scaled'); const {originW, originH} = $currentImg.data(); if (isScaled) { // 切换为适配窗口大小模式 $currentImg.animate({ width: "90vw", height: "auto" }, 300).removeClass('scaled'); } else { // 切换为原始尺寸模式 $currentImg.animate({ width: `${originW}px`, height: `${originH}px` }, 300).addClass('scaled'); // 动画完成后滚动到图片居中位置 setTimeout(() => { this.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center' }); }, 300); } }); }); </script> </html>
关键改动说明
- 页面资源加载完成后预先缓存每张图片的原始宽高,动画切换时直接使用具体像素值作为目标参数,避免
auto/none导致的动画失效问题 - 给图片添加
transition属性实现平滑过渡效果,同时通过cursor属性区分两种状态的交互提示 - 缩放完成后延迟触发
scrollIntoView,传入居中参数保证缩放后的图片在视口中居中展示 - 避免了原始尺寸图片撑开页面后导致的滚动阻塞问题,两种状态切换时页面布局逻辑一致
内容的提问来源于stack exchange,提问作者Alexandre D.
相关产品推荐
相关产品推荐

