Header 页面刷新时数组的颜色变化(Squarespace)

Header colour change from array on page refresh (Squarespace)

我相信我真的很接近,但不知道我哪里出错了。

<script type="text/javascript">
//colour change on refresh
var colorArray = ["#003D44", "#096570", "#164487", "#FFFF99", "#2252A0", "#72220D"];
const headerr = document.querySelector('.header-announcment-bar-wrapper')
function getRandomColor() {
  return colorArray[Math.random() * colorArray.length | 0];
}

console.log(getRandomColor());

window.addEventListener('load', ()=> {
    headerr.style.backgroundColor * getRandomColour
});
</script>

将以下内容添加到 FOOTER 代码注入:

<script type="text/javascript">
  // Randomly set background color of Announcement Bar Wrapper.
  const headerABW = document.querySelector('.header-announcement-bar-wrapper');
  const colorArray = ["#003D44", "#096570", "#164487", "#FFFF99", "#2252A0", "#72220D"];
  headerABW.style.backgroundColor = colorArray[Math.floor(Math.random() * colorArray.length)];
</script>

重要的是将其添加到页脚代码注入中,以便在执行代码时出现该元素。这消除了对事件侦听器的需要。

函数声明也不需要;背景颜色可以直接设置。

你也有错别字; 'announcement'.

中缺少 'e'

同样值得注意的是,如果随机选择与之前相同的颜色,则颜色可能不会随着每次刷新而改变。有一些方法可以存储最后选择的颜色并确保在页面刷新时加载不同的颜色。