1. CSS만 이용한 버튼 호버 효과
아래 예제는 JavaScript 없이 순수 CSS만으로 버튼에 마우스를 올렸을 때 배경색이 바뀌고, 살짝 위로 올라가는 애니메이션 효과를 구현한 것입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS 호버 예제</title>
<style>
.hover-button {
background-color: #3498db;
color: white;
border: none;
padding: 12px 24px;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s ease;
}
.hover-button:hover {
background-color: #2980b9;
transform: translateY(-2px);
}
.hover-button:active {
background-color: #1c5980;
transform: translateY(0);
}
</style>
</head>
<body>
<button class="hover-button">CSS 호버 버튼</button>
</body>
</html>
2. 바닐라 자바스크립트로 직접 이벤트 처리하기
이 예제는 JavaScript의 `mouseover`와 `mouseout` 이벤트를 사용하여, 버튼에 마우스를 올리면 색상과 텍스트를 변경하는 동적인 기능을 보여줍니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript 호버 예제</title>
<style>
.js-button {
background-color: #e74c3c;
color: white;
border: none;
padding: 12px 24px;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.js-button:hover {
color: #ffebeb;
}
</style>
</head>
<body>
<button id="jsHoverBtn" class="js-button">JS 호버 버튼</button>
<script>
const btn = document.getElementById('jsHoverBtn');
function handleMouseOver() {
btn.style.backgroundColor = '#c0392b';
btn.textContent = '마우스 오버 중';
}
function handleMouseOut() {
btn.style.backgroundColor = '#e74c3c';
btn.textContent = 'JS 호버 버튼';
}
btn.addEventListener('mouseover', handleMouseOver);
btn.addEventListener('mouseout', handleMouseOut);
</script>
</body>
</html>
3. CSS + JS 결합 예제
이 예제는 CSS로 기본적인 애니메이션 효과를 주면서, JavaScript로 마우스 이벤트에 대한 경고(alert)나 로그 출력도 같이 처리하는 복합 방식입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CSS + JS 호버 결합 예제</title>
<style>
.combo-button {
background-color: #2ecc71;
color: white;
border: none;
padding: 12px 24px;
font-size: 16px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s ease;
}
.combo-button:hover {
background-color: #27ae60;
transform: translateY(-2px);
}
</style>
</head>
<body>
<button id="comboBtn" class="combo-button">CSS+JS 버튼</button>
<script>
const comboBtn = document.getElementById('comboBtn');
comboBtn.addEventListener('mouseover', function() {
alert('버튼에 마우스를 올리셨습니다!');
});
comboBtn.addEventListener('mouseout', function() {
console.log('마우스가 버튼에서 벗어났습니다.');
});
</script>
</body>
</html>
댓글 없음:
댓글 쓰기