繁体   English   中英

JavaScript在div悬停时更改全局变量

[英]Javascript change global variable on div Hover

如何在div悬停时更改全局var值。

当我将鼠标悬停.mehover.mehoverAnother类上时,该类' hideplease '将添加到.mehide.mehideAnother hoverOut上时,删除类.mehide.mehideAnother但将类的删除延迟2秒,并且如果我每次将鼠标悬停在.mehover.mehoverAnother请将timetolive变量值更改为0。

请参阅下面的代码:

Java脚本

var timetolive = 2000;
$(document).ready(function() {
  $('.meHover').hover(function() {
        //code here to change the timetolive var value 
        //the .mehide or .mehideAnother should hide immediately by changing the timetolive var value to 0
        $('.mehide').addClass('hideplease');
  }, function() {
        setTimeout(function(){ $('.mehide').removeClass('hideplease'); }, timetolive); //delay removal of class
  });

  $('.meHoverAnother').hover(function() {
        //code here to change the timetolive var value 
        //the .mehide or .mehideAnother should hide immediately by changing the timetolive var value to 0
        $('.mehideAnother').addClass('hideplease');
  }, function() {
        setTimeout(function(){ $('.mehideAnother').removeClass('hideplease'); }, timetolive); //delay removal of class
  });
});

的HTML

<div class="container">
  <div class="meHover">hoverme</div>
  <div class="meHoverAnother">other hoverme</div>

  <div class="mehide"></div>
  <div class="mehideAnother"></div>
</div>

jsfiddle示例在这里https://jsfiddle.net/pqn01e5h/9/

试试下面的代码。

 var timetolive = 2000; $(document).ready(function() { $('.meHover').hover(function() { timetolive = 0; $('.mehide').addClass('hideplease'); }, function() { timetolive = 2000; setTimeout(function(){ $('.mehide').removeClass('hideplease'); }, timetolive); //delay removal of class }); $('.meHoverAnother').hover(function() { timetolive = 0; $('.mehideAnother').addClass('hideplease'); }, function() { timetolive = 2000; setTimeout(function(){ $('.mehideAnother').removeClass('hideplease'); }, timetolive); //delay removal of class }); }); 
 .container { width: 100%; height: 100%; color: white; } .meHover { width: 120px; height: 40px; background: red; margin: 20px 0 0 0; position: absolute; } .meHoverAnother { width: 120px; height: 40px; background: blue; margin: 20px 0 0 120px; position: absolute; } .mehide { width: 120px; height: 40px; background: yellow; position: absolute; margin: 60px 0 0 0; } .mehideAnother { width: 120px; height: 40px; background: orange; position: absolute; position: absolute; margin: 60px 0 0 120px; } .hideplease { display: none; opacity: 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="meHover">hoverme</div> <div class="meHoverAnother">other hoverme</div> <div class="mehide"></div> <div class="mehideAnother"></div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM