如何创建中间图片放大、尺寸渐变的随机数量图片画廊?
实现中间放大、向两侧尺寸递减的图片画廊
想要创建一个中间图片放大,向两侧尺寸依次递减的图片画廊,图片数量随机,效果参考下图:
目前已通过代码定位到中间元素,但不知道如何实现从中间向两侧的尺寸渐变效果,现有代码如下:
现有代码
JavaScript
var boxes = document.querySelectorAll(".box"); var middle = boxes[Math.round((boxes.length - 1) / 2)]; middle.style.width = "70px" middle.style.height= "70px"
CSS
.container{ display:flex; justify-content:center; align-items:center; } .box{ width:50px; height:50px; background-color:black; margin:10px; }
HTML
<div class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> <div class="box"></div> </div>
实现方案
核心思路是计算每个元素到中间元素的距离,根据距离调整尺寸——距离中间越远,尺寸越小,适配任意数量的图片。
修改后的JavaScript代码
const boxes = document.querySelectorAll(".box"); const middleIndex = Math.round((boxes.length - 1) / 2); const baseSize = 50; // 基础尺寸 const increment = 10; // 每靠近中间一级增加的尺寸 boxes.forEach((box, index) => { // 计算当前元素到中间的距离(绝对值) const distance = Math.abs(index - middleIndex); // 计算尺寸:中间元素最大,每向外一级尺寸递减increment const size = baseSize + (increment - distance * increment); // 避免尺寸过小,设置下限 const finalSize = Math.max(size, baseSize - increment * 2); box.style.width = `${finalSize}px`; box.style.height = `${finalSize}px`; });
可选优化:平滑渐变效果
如果需要更自然的尺寸过渡,可以用线性渐变公式替代固定增量:
const boxes = document.querySelectorAll(".box"); const middleIndex = Math.round((boxes.length - 1) / 2); const maxSize = 70; // 中间元素最大尺寸 const minSize = 40; // 两侧最小尺寸 // 计算最远元素到中间的距离 const maxDistance = Math.max(middleIndex, boxes.length - 1 - middleIndex); boxes.forEach((box, index) => { const distance = Math.abs(index - middleIndex); // 按比例计算当前尺寸 const size = maxSize - ((maxSize - minSize) / maxDistance) * distance; box.style.width = `${size}px`; box.style.height = `${size}px`; });
内容的提问来源于stack exchange,提问作者HamiD
相关产品推荐
相关产品推荐

