【问题标题】:jQuery detect if mouse clicked between mouseenter and mouseleavejQuery检测鼠标是否在mouseenter和mouseleave之间单击
【发布时间】:2016-01-22 08:21:00
【问题描述】:

我正在为评级系统制作一个小脚本,目前有 3 个功能:

  1. 悬停:

    a. On mouse enter change the color of div depending on value
    b. On mouse leave revert back to white
    
  2. 点击:

    a. On click save color change and put value in another div
    

    现在我需要检查是否在 mouseleave 之前单击了其中一个 div,因为如果您选择了该 div,我需要颜色保持与离开 div 时鼠标单击时的颜色相同。

我该如何检查?

这是我的 div 构造:

<div class='rating' data-target="tijd">
    <div class='circle'>1</div>//green
    <div class='circle'>2</div>//green
    <div class='circle'>3</div>//green
    <div class='circle'>4</div>//green
    <div class='circle'>5</div>//green
    <div class='circle'>6</div>//green
    <div class='circle'>7</div>//green
    <div class='circle'>8</div>//white
    <div class='circle'>9</div>//white
    <div class='circle'>10</div>//white
    <div class='score'><span id="tijd">7</span></div>
</div>

所以$('.circle').on('hover', function(e){}, function(e){}),然后是$('.circle').on('click', function(e){}),所以 click 函数被 mouse-leave 函数覆盖,因为 mouseleave 函数稍后被调用。

在“#tijd”跨度中,我保存了您单击的 div 的值,在悬停时,我需要小于或等于跨度的每个 div 更改为某种颜色,而所有大于该值的 div是白色的,如果您不单击任何内容,则 div 应使用仍在范围内的值再次着色。

(我已经尝试检查保存点击值的 div 是否不为空,但它从来不是)

$('.circle').hover(function(e) {
  $(this).siblings().css('background-color', 'white')
  val = parseInt($(this).text(), 10)
  $(this).prevAll('.circle').each(function() {
    if (val < 4 && val > 0)
      $(this).css('background-color', 'red')
    if (val < 7 && val > 3)
      $(this).css('background-color', 'orange')
    if (val < 11 && val > 6)
      $(this).css('background-color', 'green')
  })
  val = parseInt($(this).text(), 10)
  console.log(val)
  if (val < 4 && val > 0)
    $(this).css('background-color', 'red')
  if (val < 7 && val > 3)
    $(this).css('background-color', 'orange')
  if (val < 11 && val > 6)
    $(this).css('background-color', 'green')
}, function(e) {
  spanid = spanid = $(this).parent().attr('data-target')
  text = $('#' + spanid).text()
  console.log(text)
  if ($('#' + spanid) == '') {
    $(this).siblings('.circle').css('background-color', 'white')
    $(this).css('background-color', 'white')
  } else {
    val = parseInt(text, 10)
    if (val < 4 && val > 0)
      color = 'red'
    if (val < 7 && val > 3)
      color = 'orange'
    if (val < 11 && val > 6)
      color = 'green'
    $(this).prevAll('.circle').each(function() {
      if ($(this).text() <= text) {
        console.log('smaller or equal to')
        next.css('background-color', color)
      }
      if (text.val() == "") {
        $(this).css('background-color', 'white')

      } else {
        console.log('bigger')
        $(this).css('background-color', 'white')
      }
    })
  }
})
$('.circle').click(function(e) {
  console.log('get clicked')
  spanid = $(this).parent().attr('data-target')
  val = parseInt($(this).text(), 10)
  $('#' + spanid).text(val)
  console.log('Value = ' + val)
  next = $('#' + spanid).parent()
  if (val < 4 && val > 0)
    color = 'red'
  if (val < 7 && val > 3)
    color = 'orange'
  if (val < 11 && val > 6)
    color = 'green'
  next.css('background-color', color)
  $(this).prevAll('.circle').css('background-color', color)

})
.reviews {
  background-color: white;
  display: table;
  width: 100%;
}
.rating {
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
}
.circle {
  display: table-cell;
  height: 25px;
  width: 25px;
  text-align: center;
  border: solid 2px black;
  border-radius: 100%;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-md-10 col-md-offset-2">
  <label>Tarief</label>
  <div class='rating' data-target="tarief">
    <div class='circle'>1</div>
    <div class='circle'>2</div>
    <div class='circle'>3</div>
    <div class='circle'>4</div>
    <div class='circle'>5</div>
    <div class='circle'>6</div>
    <div class='circle'>7</div>
    <div class='circle'>8</div>
    <div class='circle'>9</div>
    <div class='circle'>10</div>
    <div class='score'><span id="tarief"></span>
    </div>
  </div>
</div>
<div class="form-group col-md-10 col-md-offset-2">
  <label>Reactietijd en bereikbaarheid</label>
  <div class='rating' data-target="tijd">
    <div class='circle'>1</div>
    <div class='circle'>2</div>
    <div class='circle'>3</div>
    <div class='circle'>4</div>
    <div class='circle'>5</div>
    <div class='circle'>6</div>
    <div class='circle'>7</div>
    <div class='circle'>8</div>
    <div class='circle'>9</div>
    <div class='circle'>10</div>
    <div class='score'><span id="tijd"></span>
    </div>
  </div>
</div>

【问题讨论】:

  • 我可能遗漏了一些东西,但是元素如何在没有先触发hover 事件的情况下触发click 事件?在我看来,如果一个元素是clicked,它应该已经在hover。
  • 它是,但问题是点击事件被悬停事件覆盖
  • 大声笑,你的分号在哪里。你的语法很差。看看下面的例子。
  • @magreenberg 很抱歉,您知道 jquery 不需要分号吗?
  • 是的,jquery 是一个 javascript 库。您需要以分号结束语句。在某些情况下您不需要它,但无论如何放入它们并没有什么坏处。

标签: javascript jquery mouseevent


【解决方案1】:

我会用 CSS 和一个类来做:

  1. 使用 CSS :hover 规则设置鼠标光标悬停在元素上时的颜色
  2. 点击时,在元素上设置一个类以表明它已被选中
  3. 根据该类为元素设置样式

示例:

$(document.body).on("click", ".rating > .circle", function() {
  $(this).toggleClass("selected").siblings().removeClass("selected");
});
.rating {
  padding: 2px;
}
.rating .circle {
  padding: 6px;
  display: inline-block;
  width: 2em;
  text-align: center;
}

/* When hovering, use a yellow background */
.rating > .circle:hover {
  background-color: yellow;
}

/* Selected items have a blue background and white text */
.rating > .circle.selected,
.rating > .circle.selected:hover {
  background-color: blue;
  color: white
}
<div class="rating">
  <div class="circle">1</div>
  <div class="circle">2</div>
  <div class="circle">3</div>
  <div class="circle">4</div>
  <div class="circle">5</div>
  <div class="circle">6</div>
  <div class="circle">7</div>
  <div class="circle">8</div>
  <div class="circle">9</div>
  <div class="circle">10</div>
</div>
<div class="rating">
  <div class="circle">1</div>
  <div class="circle">2</div>
  <div class="circle">3</div>
  <div class="circle">4</div>
  <div class="circle">5</div>
  <div class="circle">6</div>
  <div class="circle">7</div>
  <div class="circle">8</div>
  <div class="circle">9</div>
  <div class="circle">10</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

【讨论】:

  • 这个方案的问题是hoverout事件还是会覆盖click事件
  • @FMashiro:不,不会。请参阅示例。
  • 查看我的 sn-p 了解我的意思
  • @FMashiro:上述解决方案有效。试试看。如果出于某种原因您不想使用它,则不必使用它,但它确实有效。做你正在做的颜色的事情只需要很少的调整。
  • 我将重写我的代码以适应这一点,感谢您的帮助
【解决方案2】:

假设元素的默认背景色定义为

div.rating .circle
{
   background-color: #000; 
}

悬停颜色变为

div.rating .circle:hover
{
   background-color: #ff0; 
}

在点击事件中设置另一个类'selected',这样当鼠标离开时颜色变为#dedede;

$( "div.rating .circle" ).click( function(){

   $( this ).toggleClass( "selected" );

} );

div.rating .circle.selected
{
   background-color: #dedede; 
}

也为selected 类定义悬停行为

div.rating .circle.selected:hover
{
   background-color: #dedede; 
}

【讨论】:

    【解决方案3】:

    我想在鼠标进入和离开时添加和删除一个类并在点击时检查该类是一种方便的方法。

    //add and remove a focus class with the same css values as the active class
    $('.yourclass').on('mouseenter',function(){
        $('.yourclass').addClass('focussed');
    }).on('mouseleave',function(){
        $('.yourclass').removeClass('focussed');
    });
    
    //check only for clicks on the focussed element and add the active class
    $('.yourclass.focussed').on('click',function(){
        $(this).addClass('active');
    });
    

    【讨论】:

      【解决方案4】:

      您可以通过将 .click() 函数添加到您的 jQuery 中来做到这一点,如下所示:

      请注意,所有这些都是示例代码

      HTML

      <div class="colors">
        <div class="red"></div>
        <div class="blue"></div>
        <div class="green"></div>
        <div class="yellow"></div>
        <div class="pink"></div>
      </div>
      

      CSS

      .red {
        background-color:red;
      }
      .blue {
        background-color:blue;
      }
      .green {
        background-color:green;
      }
      .yellow {
        background-color:yellow;
      }
      .pink {
        background-color:pink;
      }
      div {
        height:40px;
        width:40px;
      }
      div.colors {
        width:200px;
        height:40px;
      }
      

      jQuery**

      $( "div" ).not('.colors')
      .mouseenter(function() {
          //do something
         })
      .mouseleave(function() {
          //do something
        })
      .click(function() {
        var color = $(this).css('background-color');
        alert(color);
      });
      

      Jsfiddle example

      希望这会有所帮助!

      【讨论】:

        【解决方案5】:

        您可以使用 jquerys .hover() 函数代替 mousein mouseout。

        HTML

        <div class="boxy">
        
        </div>
        
        <div class="selected">
          <h1>Selected Color From Click</h1>
        </div>
        

        CSS

        * {box-sizing: border-box;}
        .boxy{
          border: 2px solid #000;
          width: 400px;
          height: 400px;
        }
        .selected{
          border: 2px solid #000;
        }
        

        JS

        var colors = ["#34f23a", "#f8f8f1", "#31b1cc"];
        var changecolors;
        var colorIndex = 0;
        
        $('.boxy').hover(function(){
          shuffle = true;
          $(this).css('background', colors[colorIndex]);
          changecolors = setInterval(function(){
            if (colorIndex < (colors.length - 1)){
              colorIndex += 1;
            } else {
              colorIndex = 0;
            }
            $('.boxy').css('background', colors[colorIndex]);
          },500);
        
        }, function(){
          window.clearInterval(changecolors);
          $('.boxy').css('background', 'transparent');
        });
        
        $('.boxy').click(function(){
           var selectedColor = $(this).css('background');
           $('.selected').css('background', selectedColor);
        });
        

        JSFiddle Example

        【讨论】:

        • 这就是我做的,除了问题出在哪里,看看我添加的sn-p
        【解决方案6】:

        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <title>js functions</title>
          <style>
            body { background-color:#101010; color: #aaa; text-align: center;}
            #holder{ width: 100%; height:100px; margin: 0 auto; display: inline-block;}
            #hover { position: relative; border: 1px dashed #333; width:100px; height:100px; display: inline-block;}
            #save  { border: 1px dashed #333; width:100px; height:100px; display: inline-block;}
          </style>
          <script>
            document.onreadystatechange = function()
            {
              
              var hover = document.getElementById("hover");
              var save  = document.getElementById("save");
        
              hover.onmouseover = function()
              {
                hover.style.background = "#f00";
              };
        
              hover.onmouseout = function()
              {
                hover.style.background = "#101010";
              };
        
              hover.onclick = function()
              {
                save.style.background = "#fff";
              };
            }
          </script>
        </head>
        <body>
          <div id="holder">
          <div id="hover">hover</div><div id="save">save</div>
           </div>
        </body>
        </html>

        【讨论】:

          猜你喜欢
          • 2011-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多