编辑:我遇到的唯一问题是缺少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>
&#13;
答案 0 :(得分:1)
当鼠标悬停在按钮上时,此代码会每秒更改颜色 - 如果这不是您的意图,那么您唯一的问题就是缺少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;
});
&#13;
div {
background: red;
width: 100px;
height: 100px;
}
&#13;
<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>
&#13;
答案 1 :(得分:1)
这个会改变每个mouseover
的颜色。
我拿出了setInterval
,因为我无法理解你为什么需要这个......?
$("#myBtn").mouseover(function() {
$("#myDiv").css("background-color", "#" + Math.floor((Math.random() * 1000000) + 1));
});
&#13;
div {
background: red;
width: 100px;
height: 100px;
}
&#13;
<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>
&#13;
答案 2 :(得分:1)
尝试使用以下代码替换您的代码
var number;
var newColor;
$("#myBtn").mouseover(function() {
number = Math.floor((Math.random() * 1000000) + 1);
newColor = "#" + number;
$("#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>
答案 3 :(得分:0)
在codepen上它对我有用,如果你想在鼠标上面获得一种新颜色而不是鼠标移动,你应该将mouseout设置为相同的颜色。
答案 4 :(得分:0)
我遇到的唯一问题是缺少jQuery