gpt4 book ai didi

Javascript - 每次鼠标悬停时生成新颜色

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:55 25 4
gpt4 key购买 nike

编辑:我遇到的唯一问题是缺少 jQuery


我的 code应该在每次鼠标悬停时生成一种新颜色,但它不起作用你能告诉我问题出在哪里吗?

var number;
var newColor;
setInterval(function() {
number = Math.floor((Math.random() * 1000000) + 1);
newColor = "#" + number;
}, 1000);
$("#myBtn").mouseover(function() {
$("#myDiv").css("background-color", newColor);
});
div {
background: red;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="myBtn">Hover Here To Change Color</button>
<div id="myDiv"></div>

最佳答案

这段代码会在鼠标悬停在按钮上时每秒更改颜色 - 如果这不是您的意图,那么您遇到的唯一问题就是缺少 jQuery

var isOver = false; // only required if colour should change continuously
var newColor;
setInterval(function() {
var number = Math.floor((Math.random() * 1000000) + 1);
newColor = "#" + number;
// next 3 lines only required if colour should change continuously
if(isOver) {
$("#myDiv").css("background-color", newColor);
}
}, 1000);
$("#myBtn").mouseover(function() {
isOver = true; // only required if colour should change continuously
$("#myDiv").css("background-color", newColor);
});
// next 3 lines only required if colour should change continuously
$("#myBtn").mouseout(function() {
isOver = false;
});
div {
background: red;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myBtn">Hover Here To Change Color</button>
<div id="myDiv"></div>

关于Javascript - 每次鼠标悬停时生成新颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35392055/

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