我正在开发一个项目,当我更改颜色时,我很难编写出使项目中的球更改为与左上角按钮相同的颜色所需的代码。我需要他们保持同步。需要记住的一些事情是没有 jquery 纯 vanilla javascript 和 ecma 5
话虽如此,这里是该项目的说明:
Use Javascript form events to adjust the background colour of a circle on the screen.
- Fork this repository.
- **Make a
<form>
tag with an<input>
inside it—usetype="color"
for the input.- When the form’s
change
event fires, adjust thebackground-color
of the ball to match the input’s value.- Run it through Markbot and make sure it passes all the checks.
这是我的项目当前的样子:
当我点击左上角的按钮时,会弹出:
这是我的 html:
<!DOCTYPE html>
<html>
<head>
<title>CircleColourr</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="ball"></div>
</body>
<script src="jquery.min.js"></script>
<script src="main.js"></script>
</html>
这是我的 main.css
html{
box-sizing: border-box;
}
*, *::before, *::after{
box-sizing: inherit;
}
.ball{
width: 200px;
height: 200px;
position: absolute;
top: 200px;
left: 200px;
background-color: ;
border-radius: 100px;
}
这是我的 main.js
var body = document.querySelector('body');
var h2 = document.createElement('h3');
var forma = document.createElement('form');
var inForma = document.createElement('input');
var h2 = document.createTextNode('Colour');
inForma.type = 'color';
inForma.id = 'listen';
body.appendChild(h2);
forma.appendChild(inForma);
body.appendChild(forma);
var bally = document.querySelector('.ball');
bally.style.backgroundColor = forma; // first attempt
console.log(bally.style.backgroundColor = forma);//first attempt
var button = document.getElementById('listen').addEventListener ('click', change);
function change(e){
document.querySelector('.ball').style.backgroundColor = forma;
}
我做了两次尝试,第一个只是将实际的表单元素分配给球 div,第二个似乎什么也没发生。我的思考过程是将形式分配给球的背景颜色。我只是需要一些指导。
最佳答案
我发现有几个问题
这里有一个空格,会破坏它
getElementsById
不是有效函数,请使用 getElementById
当您打开用户界面时,事件监听器 click
将触发,您想使用 change
监听器,在用户选择颜色后更新值
var button = document.getElementsById('listen').addEventListener('点击',change);
您没有带有名为 class
的类的元素,但您确实有 .ball
document.querySelector('.class').style.backgroundColor
这是一个工作版本 https://jsfiddle.net/rp9kxLyu/
关于javascript - 将一个元素的颜色值链接到另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51448639/