如何在鼠标移动到屏幕上的任何位置时显示div,而不仅仅是元素本身?

时间:2016-12-07 15:43:15

标签: javascript jquery reactjs

当用户将鼠标移到特定元素上时,我设法隐藏并显示我的类。但我真正想要的是,这些显示当用户将鼠标移动到屏幕上的任何位置时,而不仅仅是选定的div。

这是我目前的代码:

$(window).on('mousemove', function () {
  $('.barhide').addClass('show');
  try {
    clearTimeout(timer);
  } catch (e) {}
  timer = setTimeout(function () {
    $('.barhide').removeClass('show');
  }, 1000);
});

我的css:

.barhide {
  background: #333;
  color: #fff;
  display: block;
  opacity: 0;
  transition: all 1.5s ease;
}

.barhide.show {
  opacity: 1;
  display: none;
}

所以我想要的是,在3秒之后,带有.barhide的类会被隐藏,如果用户将鼠标移动到屏幕的任何位置,它们会再次出现,而不是仅仅当它们移动到元素上时。

此外,我想知道用React做这些事情并不容易吗?

2 个答案:

答案 0 :(得分:2)

我对代码进行了重组,并添加了一些评论,解释了发生了什么以及何时发生。此外,丢失try因为尝试清除计时器永远不会抛出异常。

请注意,mouseover类型事件是移动设备上的问题。这两篇文章在这方面可能有所帮助:

JQuery's Virtual Mouse Events

Simulated Mouse Events using JQuery



$(function(){
  // When page loads, wait 3 seconds and hide all elements with .barhide class:
  setTimeout(toggle, 3000);
});

var timer = null;

// General function for adding/removing the "hide" class.
// This is used when the page first loads and each time
// the mouse moves on the page. We're not calling toggle()
// here because a flicker effect can happen which would leave
// the elements showing instead of being hidden.
function toggle(){
  $('.barhide').toggleClass('hide');
}

$(window).on('mousemove', function(){
  // When anywhere on page is moused over bring back .barhide
  // elements for 3 seconds. Removing "hide" simply restores
  // the original CSS & layout
  $('.barhide').removeClass('hide');
  
  // Kill any previous timers
  clearTimeout(timer);
  
  // Wait 3 seconds and hide again
  timer = setTimeout(toggle, 3000)
});

.barhide { background-color:blue; }
.hide { display:none; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="barhide">ONE</div>
<div class="show">TWO</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你只计算正在运行的计时器的数量,当最后一个结束时你隐藏吧。

var count = 0;

$(window).mousemove(function( event ) {
  $('.barhide').show();
  count += 1;

  setTimeout(function() {
    if (count == 1) {
      $('.barhide').hide();
    }
    count -= 1;
  }, 3000);
});