gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
使用js写一个颜色选择器
- User
使用js写一个颜色选择器
- Assistant
以下是一个使用JavaScript编写的简单颜色选择器示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Color Picker</title> <style> .color-sample { width: 50px; height: 50px; display: inline-block; border: 1px solid #000; cursor: pointer; } </style> </head> <body> <div id="color-picker"> <div class="color-sample" id="color-sample-red"></div> <div class="color-sample" id="color-sample-green"></div> <div class="color-sample" id="color-sample-blue"></div> </div> <script> function changeColor(color) { document.body.style.backgroundColor = color; } document.getElementById('color-sample-red').addEventListener('click', function() { changeColor('red'); }); document.getElementById('color-sample-green').addEventListener('click', function() { changeColor('green'); }); document.getElementById('color-sample-blue').addEventListener('click', function() { changeColor('blue'); }); </script> </body> </html>该示例中包含了三个颜色示例块,通过JavaScript的事件监听方法
addEventListener,分别为每个示例块绑定了一个点击事件。点击颜色示例块后,调用changeColor函数,将背景颜色设置为相应的颜色值。 - User
表示“颜色选择器”的变量名
- Assistant
我们可以为颜色选择器的变量设置一个更具体的名称,如"colorPicker"。
以下是使用"colorPicker"作为颜色选择器变量名的示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Color Picker</title> <style> .color-sample { width: 50px; height: 50px; display: inline-block; border: 1px solid #000; cursor: pointer; } </style> </head> <body> <div id="color-picker"> <div class="color-sample" id="color-sample-red"></div> <div class="color-sample" id="color-sample-green"></div> <div class="color-sample" id="color-sample-blue"></div> </div> <script> function changeColor(color) { document.body.style.backgroundColor = color; } var colorPicker = document.getElementById('color-picker'); var redSample = document.getElementById('color-sample-red'); var greenSample = document.getElementById('color-sample-green'); var blueSample = document.getElementById('color-sample-blue'); redSample.addEventListener('click', function() { changeColor('red'); }); greenSample.addEventListener('click', function() { changeColor('green'); }); blueSample.addEventListener('click', function() { changeColor('blue'); }); </script> </body> </html>