JavaScript随机排序图片数组时固定g.jpg在中间位置的方法
图片随机排序固定g.jpg在中间位实现方案
核心实现逻辑
不需要复杂的DOM位置重排,只需要在洗牌阶段把固定项排除,洗牌完成后再把固定项插入到中间位置即可,同时渲染时给固定项添加专属类名方便样式控制:
- 从原数组中拆分出固定项
images/g.jpg,剩余图片组成待随机数组 - 仅对待随机数组执行洗牌逻辑,避免固定项被打乱
- 计算数组中间索引,将固定项插入到随机后数组的正中间位置
- 渲染时判断当前图片地址,为
g.jpg添加专属类名
修改后完整代码
<html> <head> <meta charset='utf-8'> <title>图片随机排序</title> <style> .ppl{ width: 250px; } /* 固定项专属样式,可按需自定义 */ .fixed-middle{ /* 可在这里添加中间位置的固定样式,比如特殊边框、尺寸标记等 */ border: 2px solid red; } </style> </head> <body> <div id="root"></div> <script type="text/javascript"> const images = [ 'images/1.jpg', 'images/2.jpg', 'images/g.jpg', 'images/3.jpg', 'images/4.jpg' ] const root = document.querySelector('#root') const shuffle = ([...array]) => { let currentIndex = array.length let temporaryValue let randomIndex while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex) currentIndex -= 1 temporaryValue = array[currentIndex] array[currentIndex] = array[randomIndex] array[randomIndex] = temporaryValue } return array } // 1. 拆分固定项和待随机项 const fixedImage = 'images/g.jpg' const needShuffleImages = images.filter(src => src !== fixedImage) // 2. 仅对非固定项洗牌 const shuffledPart = shuffle(needShuffleImages) // 3. 计算中间索引,插入固定项(5个元素时中间索引为2,正好是第3位正中间) const insertIndex = Math.floor(shuffledPart.length / 2) shuffledPart.splice(insertIndex, 0, fixedImage) // 4. 渲染最终列表 shuffledPart.forEach(src => { const image = document.createElement('img') image.src = src image.alt = src image.classList.add('ppl') image.classList.add('pos') // 给固定图添加专属类名 if (src === fixedImage) { image.classList.add('fixed-middle') } root.appendChild(image) }) </script> </body> </html>
实现说明
- 该实现不会修改原数组结构,每次刷新页面除了中间的
g.jpg,其余图片都会随机排列 - 专属类
fixed-middle可以按需添加样式,比如标记固定图、调整固定图的显示效果 - 如果后续图片总数变化,
Math.floor(shuffledPart.length / 2)会自动计算中间位置,不需要手动修改索引值
内容的提问来源于stack exchange,提问作者Zhewar
相关产品推荐
相关产品推荐

