使用javascript进行随机颜色更改

使用javascript进行随机颜色更改,javascript,Javascript,按钮作业 函数优先(){ document.getElementById('type1')。style.position='absolute'; document.getElementById('type1').style.left=“100px”; document.getElementById('type1').style.top=“200px”; var red=Math.floor(Math.random()*256); var green=Math.floor(Math.random(


按钮作业
函数优先(){
document.getElementById('type1')。style.position='absolute';
document.getElementById('type1').style.left=“100px”;
document.getElementById('type1').style.top=“200px”;
var red=Math.floor(Math.random()*256);
var green=Math.floor(Math.random()*256);
var blue=Math.floor(Math.random()*256);
var newColor=“rgb(“+红色+”、“+绿色+”、“+蓝色+”);
}
函数第二(){
document.getElementById('type1')。style.position='absolute';
document.getElementById('type1').style.left=“0px”;
document.getElementById('type1').style.top=“80px”;
}
特殊按钮

只需将颜色指定给样式属性即可。在这种情况下,按钮的背景色

function first() {
  var red = Math.floor(Math.random() * 256);
  var green = Math.floor(Math.random() * 256);
  var blue = Math.floor(Math.random() * 256);

  var newColor = "rgb(" + red + "," + green + "," + blue + ")";
  document.getElementById("type1").style.backgroundColor = newColor;
}

如果你想让你的作业看起来像是从互联网上抄来的:


按钮作业
#类型1{
位置:绝对;}
#类型1.mouseover{
左:100px;
顶部:200px;}
#类型1:不是(.mouseover){
左:0px;
顶部:80px;}
特殊按钮
功能鼠标盖(按钮){
button.classList.add('mouseover');
//将backgroundColor设置为随机十六进制字符串
button.style.backgroundColor='#'+Math.floor(Math.random()*16777215).toString(16);
}
功能鼠标输出(按钮){
button.classList.remove('mouseover');
}
函数输出(){
//不管这有什么用
}

嗨,凯文,你的意思是要将鼠标上按钮的位置移到上方吗?不,但每次你将鼠标悬停在按钮上方时,按钮都会变成随机颜色。示例:开始时为白色,但当您将鼠标悬停在其上时,它将变为黑色,依此类推。Aron的回答是准确的,您从未将颜色指定给元素。但请记住,查询DOM会产生成本,因此,如果可能,请存储对需要操作的元素的引用,并尝试批处理更改以避免重复重新绘制。好的,谢谢!欢迎:)如果它解决了你的问题,你能把它标记为答案吗?