页面html,当鼠标点击图标,移开图标,颜色方块消失
html页面代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>颜色选择器</title><style>body {font-family: "Microsoft YaHei", sans-serif;padding: 20px;}.color-icon {font-size: 20px;font-weight: bold;width: 24px;height: 24px;display: inline-block;text-align: center;line-height: 24px;border: 1px solid #ccc;border-radius: 4px;cursor: pointer;user-select: none;}.color-picker {display: none;position: absolute;background-color: white;border: 1px solid #ccc;padding: 5px;grid-template-columns: repeat(9, 10px);gap: 5px;margin-top: 5px;z-index: 10;}.color-box {width: 10px;height: 10px;cursor: pointer;border: 2px solid #ccc;border-radius: 4px;}#text {font-size: 18px;margin-top: 40px;}</style>
</head>
<body><h2>点击"A"选择颜色:</h2><div class="color-icon" id="togglePicker">A</div>
<div class="color-picker" id="colorPicker"></div>
<div id="text">这是正文内容,点击颜色块来更改我的颜色。</div><script>const togglePicker = document.getElementById('togglePicker');const colorPicker = document.getElementById('colorPicker');const text = document.getElementById('text');// 点击“A”显示颜色选择器togglePicker.addEventListener('click', (e) => {e.stopPropagation(); // 防止冒泡到 documentcolorPicker.style.display = 'grid';const rect = togglePicker.getBoundingClientRect();colorPicker.style.top = rect.bottom + 'px';colorPicker.style.left = rect.left + 'px';});// 点击颜色改变文字颜色const colors = ['#000000', '#333333', '#666666', '#999999', '#CCCCCC', '#FFFFFF', '#FF0000', '#FF6600', '#FFFF00','#00FF00', '#00FFFF', '#0000FF', '#9900FF', '#FF00FF', '#FF9999', '#FFCC99', '#FFFF99', '#CCFFCC','#CCFFFF', '#CCCCFF', '#FFCCFF', '#660000', '#996600', '#666600', '#006600', '#006666', '#000066','#660066', '#990000', '#FF9900', '#99CC00', '#009933', '#33CCCC', '#3399FF', '#9966FF', '#CC3366','#CC0000', '#CC6600', '#999900', '#009900', '#0099CC', '#0000CC', '#9900CC', '#CC0066', '#333300'];colors.forEach(color => {const box = document.createElement('div');box.className = 'color-box';box.style.backgroundColor = color;box.addEventListener('click', () => {text.style.color = color;});colorPicker.appendChild(box);});// 鼠标点击空白处时隐藏颜色选择器document.addEventListener('click', () => {colorPicker.style.display = 'none';});// 点击颜色选择器时阻止事件冒泡colorPicker.addEventListener('click', (e) => {e.stopPropagation();});// 设置初始样式colorPicker.style.position = 'absolute';colorPicker.style.gridTemplateColumns = 'repeat(9, 10px)';
</script></body>
</html>
页面效果: