2

Как можно отследить, находится ли курсор над определенным элементом?

1

3 ответа 3

1

Вам надо подключить к элементу слушателя на событие mouseover, например так, если с jquery:

$("element_selector").on("mouseover", function(e){
 // любой код
})

если на чистом js:

document.getElementById('elementId').onmousemove = function(e){ 
 // любой код
}

Про события мыши можно почитать здесь Вот тут (на русском)

12
  • в вопросе не было упоминания jQuery.
    – Grundy
    31 окт 2016 в 13:25
  • Если без jquery, то можно так: document.getelementById('elementId').onmousemove = function(e){ // любой код}
    – Mikl
    31 окт 2016 в 13:32
  • 1
    Вынесете этот код в ответ. P. S. он не рабочий.
    – user207618
    31 окт 2016 в 13:37
  • внес рабочий, спасибо!)
    – Mikl
    31 окт 2016 в 13:42
  • @Mikl, почему в примере с jQuery mouseover, а без - mousemove?
    – Grundy
    31 окт 2016 в 13:46
0

Вариант если уже подписаны на mousemove -

document.addEventListener('mousemove', document_mouseMoveHandler);

function document_mouseMoveHandler(event) {
  let element = document.elementFromPoint(event.clientX, event.clientY);
  let isSecondValid = isSecond(element.dataset.id);

  let info = document.querySelector('.validator-output')
  info.textContent = isSecondValid;
}

function isSecond(value) {
  return value === "second"
}
main {
  padding: 15px
}
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-around;
  position: relative;
}
.child {
  width: 100px;
  height: 100px;
  background: tomato;
  text-align: center;
  display: flex;
}
.informer {
  width: 100%;
  height: 30px;
  position: relative;
  padding: 15px;
  display: flex;
  justify-content: space-around;
}
.child > span {
  color: white;
  margin: auto;
  pointer-events: none;
}
<main>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" />

  <body>
    <div class="container">
      <div class="child" data-id="first"><span>first</span>
      </div>
      <div class="child" data-id="second"><span>second</span>
      </div>
      <div class="child" data-id="third"><span>third</span>
      </div>
    </div>
    <div class="informer">
      <span>is second: <span class="validator-output">false</span></span>
    </div>
</main>

1
  • а если не подписаны?
    – Grundy
    31 окт 2016 в 14:31
0

var text = document.getElementById('text');
text.onmouseover = function(){
  this.style.color = 'red'; //курсор над элементом
}
text.onmouseleave = function(){
  this.style.color = '#000';//курсор покинул элемент
}
p{
	font-size: 40px;
}
<p id="text" >Some text</p>

1
  • Пожалуйста, постарайтесь писать более развернутые ответы. Уверен, автор вопроса был бы благодарен за ваш экспертный комментарий к приведенному выше коду. 1 ноя 2016 в 12:15

Ваш ответ

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

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