如何让::selection文本背景色从指定颜色数组随机选取
解决选中文本随机高亮背景色的问题
你只需要去掉原来的顺序计数逻辑,换成随机选取数组下标即可,同时可以优化style标签的创建方式,避免重复插入DOM元素:
修改后的代码
window.colors = [ "#F78DA7", "#CF2E2E", "#FF6900", "#FCB900", "#7BDCB5", "#00D084", "#8ED1FC", "#0693E3", "#9B51E0", ]; // 创建一个固定的style元素,避免重复插入DOM const selectionStyle = document.createElement('style'); document.head.appendChild(selectionStyle); document.addEventListener("mousedown", function () { // 生成0到数组长度-1之间的随机索引 const randomIndex = Math.floor(Math.random() * window.colors.length); const targetColor = window.colors[randomIndex]; // 更新style元素内容,替换之前的高亮样式 selectionStyle.textContent = ` ::selection { background-color: ${targetColor}; } ::-moz-selection { background-color: ${targetColor}; } ::-o-selection { background-color: ${targetColor}; } ::-ms-selection { background-color: ${targetColor}; } ::-webkit-selection { background-color: ${targetColor}; } `; });
关键改动说明
- 删掉了
window.order相关的顺序计数逻辑,不再按固定顺序切换颜色 - 用
Math.floor(Math.random() * window.colors.length)生成随机下标,从预设颜色数组里随机取色 - 改成创建单个固定style元素,每次只更新它的内容,避免多次插入style标签造成DOM冗余
内容的提问来源于stack exchange,提问作者Vox
相关产品推荐
相关产品推荐

