gpt4 book ai didi

javascript - 使用递归函数更改背景 背景颜色切换 css ids

转载 作者:行者123 更新时间:2023-11-28 02:16:04 26 4
gpt4 key购买 nike

我正在尝试使用递归函数更改通过 id 更改闪烁的主体背景颜色,该函数通过偶数/奇数条件检查来运行,并在每次执行后增加提供的参数继续。我正在使用 DOM 零级事件处理程序单击执行此函数。我看到一些奇怪的结果。

这是 html/css 及其 javascript 代码。另请参阅代码中的注释,它们解释了其他奇怪的问题。

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#style1 {
background:red;
}
#style2 {
background:black;
}
</style>
</head>

<body>
<input name="" type="button" value="Style Changer" id="button1" />
<script>
var button = document.getElementById("button1");
var background = function (y) {
alert(y); // results of background change or rest of the code only works if this alert is there which is what I don't really understand
if(y % 2 === 0) {
alert(y); // weird result: this shows 2 for no reason.
document.body.id = "style1"; // value supplied to the parameter y is 1 but taking the css property that suppose to take when the y is an even number.
var y = y + 1;
background(y);
} // End If
else {
document.body.id = "style2";
var y = y + 1;
background(y);
} //End Else

} // End of function
button.onclick = function () {
var x = 1;
background(x);
}

// Another big problem: Last but not least remove all the alert function and it will not work as it worked when there were alerts in the code.
</script>
</body>

最佳答案

这个 jsfiddle 做你似乎想要的事情,但是,它不使用递归,而是使用 jquery。

CSS

    .style0 {
background-color: red;
}
.style1 {
background-color: black;
}

Javascript/JQuery
    $(function () {
var i = 0
var background = function () {
$("body").removeClass()
.addClass("style" + i);

i = ((i + 1) % 2); //To cycle from 0 to 1
}

var intervalID = undefined;
$('#start').click(function () {
if (intervalID != undefined) {
clearInterval(intervalID);
}
intervalID = setInterval(background, 500);
});
});

HTML

注意 body 标记的起始类 style0。

    <body class="style0">
<button id="start">Start</button>
</body>

所以,这可能不是您可以接受的答案,但它确实达到了您想要的效果。

编辑:如果您确实想使用 ID 而不是类,则以下内容更适合您的问题。

这个 jsfiddle 使用 ID。更新后的代码如下。

CSS

    #style0 {
background-color: red;
}
#style1 {
background-color: black;
}

Javascript/JQuery
    $(function () {
var i = 0
var background = function () {
$("body").attr("id", "style" + i);

i = ((i + 1) % 2); //To cycle from 0 to 1
}

var intervalID = undefined;
$('#start').click(function () {
if (intervalID != undefined) {
clearInterval(intervalID);
}
intervalID = setInterval(background, 500);
});
});

HTML

注意 body 标记的起始 ID style0。

    <body id="style0">
<button id="start">Start</button>
</body>

关于javascript - 使用递归函数更改背景 <body> 背景颜色切换 css ids,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390462/

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