4

Как сделать, чтобы при наведении мышкой на элемент, его цвет менялся случайным образом каждый раз?

2 ответа 2

8

function getRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }
    
    $('div').mouseenter(function(e){
        $(this).css('background-color', getRandomColor());
    });
div {
  width: 100px;
  height: 100px;
  background: #333;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div>

</div>

Источник на функцию getRandomColor().

1

window.addEventListener('DOMContentLoaded', function() {
  document.querySelector('.hot').addEventListener('mouseenter', function() {
    this.style.backgroundPositionX = (Math.random() * 100 | 0) + '%';
  });
});
.hot {
  border: 1px dashed Gray;
  height: 100px;
  width: 100px;
  position: absolute;
  background-repeat: no-repeat;
  background-size: 7000% 100%;
  background-image: linear-gradient(to right, #FF0000, #FFA500, #FFFF00, #008000, #0000FF, #000080, #800080);
  transition: background-position 1.2s ease-in-out;
}
<div class="hot" style=""></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.