gpt4 book ai didi

javascript - 如何使用按钮更改网站的背景?

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:27 25 4
gpt4 key购买 nike

我正在尝试编写需要使用按钮更改背景的网站,但我不能...

我创建了一个按钮,它可以在单击按钮时更改背景颜色,但是在我添加图像作为背景后,它不想更改背景颜色(显然)...

<head>
<style>
:root{
--main-bg: url(https://www.the url of my bg.jpg);

}
</style> // creating a variable for the bg of my site

<style>
body {
background: var(--main-bg) repeat-x;

}
</style> // using this variable

<script>
var colors = ["#2d2d2d", "#f2f2f2"];
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("body");
if( colorIndex >= colors.length ) {
colorIndex = 0;
}
col.style.backgroundColor = colors[colorIndex];
colorIndex++;
// the js script to change the bg color
}
</script>

<script>
function backgroundHiding() {
let root = document.documentElement;

root.addEventListener("onclick", e => {
if (--main-bg) = "#2d2d2d" {
root.style.setProperty('--main-bg', " url(https://www.the urlof my bg.jpg)")
} else {
root.style.setProperty('--main-bg', "#2d2d2d")
}
// the js script to hide my img bg
}
</script>

<div class="button">
<body id='body'>
<button onclick="changeColor(); backgroundHiding();" class="lightbutton"><span>Turn On/Off the lights</span> </button>

</div> // creating the button that interact with the two js functions
</head>

我预计它会起作用,但是……嗯……不它有时会起作用,例如每 100 次 1 次,我不知道为什么...如果有人能帮助我,我将不胜感激!

https://stackblitz.com/edit/typescript-ppvsvl?embed=1&file=index.html

最佳答案

首先,你不需要额外的事件监听器:

root.addEventListener("onclick", e => {...})

第二,据我所知,您正在尝试读取 CSS 变量并在 if 语句中进行比较。这行不通:

if (--main-bg) =  "#2d2d2d"

我在这里修复了它:

https://stackblitz.com/edit/js-crl57k?file=index.html

这看起来像你想做的吗?

关于javascript - 如何使用按钮更改网站的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56312473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com