💻 代码笔记

记录一些工作中用到的代码片段和实用技巧

平滑滚动

CSS

一行 CSS 就能实现平滑滚动,简单实用

html {
  scroll-behavior: smooth;
}

自定义文本选择样式

CSS

选中下面的文字看看效果

这是一段可以自定义选择样式的文字,试试选中我!

::selection {
  background: #ff6b6b;
  color: white;
}

玻璃态效果 (Glassmorphism)

CSS

玻璃卡片

毛玻璃效果

.glass-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

打字机效果

JS

function typeWriter(element, text, speed = 100) {
  let i = 0;
  element.textContent = '';
  function type() {
    if (i < text.length) {
      element.textContent += text.charAt(i);
      i++;
      setTimeout(type, speed);
    }
  }
  type();
}

图片懒加载

HTML/JS
懒加载示例

原生支持,不需要写 JS,滚动到才加载

<img src="image.jpg" 
     loading="lazy" 
     alt="描述">

CSS 变量 (自定义属性)

CSS
主题色 1
主题色 2
主题色 3
:root {
  --primary-color: #4ecdc4;
  --secondary-color: #ff6b6b;
}

.element {
  color: var(--primary-color);
}

防抖函数 (Debounce)

JS

输入内容会延迟显示,避免频繁触发

function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

渐变文字效果

CSS

渐变文字效果

.gradient-text {
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

复制到剪贴板

JS
async function copyToClipboard(text) {
  await navigator.clipboard.writeText(text);
  console.log('已复制到剪贴板');
}

响应式网格布局

CSS
1
2
3
4
.grid {
  display: grid;
  grid-template-columns: repeat(
    auto-fit, 
    minmax(200px, 1fr)
  );
  gap: 1rem;
}

暗黑模式切换

CSS/JS
function toggleDarkMode() {
  document.body.classList.toggle('dark-mode');
}

.dark-mode {
  background: #1a1a1a;
  color: #fff;
}

CSS 工具提示

CSS
.tooltip::after {
  content: attr(data-tooltip);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: #333;
  color: white;
  padding: 0.5rem;
  border-radius: 4px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s;
}

.tooltip:hover::after {
  opacity: 1;
}