Как реализовать при следующем наведении новый цвет?
Как реализовать при следующем наведении новый цвет?
При первом наведении зелёный, при втором красный, при третьем желтый и так по кругу.
let getId = id => document.getElementById(id);
getId('block').addEventListener('mouseover', function(){
this.style.backgroundColor = 'red';
})
getId('block').addEventListener('mouseout', function(){
this.style.backgroundColor = '';
})
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
#block{
width: 350px;
height: 350px;
border-radius: 10px;
border: 2px solid #000;
background-color: violet;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="block"></div>
<script src="main.js"></script>
</body>
</html>
Ответы (2 шт):
Автор решения: Alex Sazonov
→ Ссылка
Массив с цветами + счетчик индекса добавил. В остальном код остался прежним почти.
let getId = id => document.getElementById(id);
let colors = ['red', 'green', 'yellow'];
let counter = 0;
getId('block').addEventListener('mouseover', function(){
this.style.backgroundColor = colors[counter];
if(counter >= 2) {
counter = 0;
} else {
counter++;
}
})
getId('block').addEventListener('mouseout', function(){
this.style.backgroundColor = '';
})
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
#block{
width: 350px;
height: 350px;
border-radius: 10px;
border: 2px solid #000;
background-color: violet;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="block"></div>
<script src="main.js"></script>
</body>
</html>
Автор решения: Quazimorda
→ Ссылка
$(document).ready(function() {
let color = 1;
let getId = id => document.getElementById(id);
getId('block').addEventListener('mouseover', function() {
switch (color) {
case 1: this.style.backgroundColor = 'green'; break;
case 2: this.style.backgroundColor = 'red'; break;
case 3: this.style.backgroundColor = 'yellow'; break;
default: break
}
if (color == 3)
color = 1;
else
color++;
})
})
Остальное ваше