【问题标题】:Detect mouse position with respect to an element检测鼠标相对于元素的位置
【发布时间】:2014-08-25 03:43:16
【问题描述】:

我在 html 中使用 svg 绘制了一个矩形。我需要检测屏幕上相对于该矩形的光标位置并更改其样式。 我需要做这样的事情:

if (cursor is left to the rectangle) {
    background of rectangle = red;
}
else if (cursor is right to the rectangle) {
    background of rectangle = blue;
} 

如何确定光标在矩形中的位置?

【问题讨论】:

    标签: javascript html css cursor-position


    【解决方案1】:

    你可以用 jQuery 做你想做的事

    CSS:

    body {
      cursor:pointer;
    }
    
    td {
      border:#777 1px solid;
      font-family:georgia; font-size:50px;
    }
    
    #content {
      background:green;
    }
    

    HTML:

    <input id="left"/> (left)<br/>
    <input id="width"/> (width)<br/>
    <input id="pageX"/> (pageX)<br/>
    
    <table>
      <tr>
        <td>Left</td>
        <td id="content">Center</td>
        <td>Right</td>
      </tr>
    </table>
    

    JS:

    $(document).ready(function(){
      $(document).mousemove(function(event){
        var content = $("#content");
        var left  = content.offset().left;
        var width = content.width();
        var pageX = event.pageX;
    
        $("#left").get(0).value = left;
        $("#width").get(0).value = width;
        $("#pageX").get(0).value = pageX;
    
        if (pageX<left)
          content.css({"background":"red"});
        else
        if (pageX>left+width)
          content.css({"background":"blue"});
        else
          content.css({"background":"green"});
      });
    });
    

    在这个 jsfiddle 中查看完整的 HTML、CSS、JS:http://jsfiddle.net/jondinham/95te26q6/

    【讨论】:

    • 谢谢乔恩!这是我一直在寻找的解决方案。
    【解决方案2】:

    你可以试试这个:

     $(document).ready(function(){
     (function() {
            window.onmousemove = handleMouseMove;
            function handleMouseMove(event) {
                event = event || window.event;
                var rect = $("#rect");
                 var left  = rect.position().left;
                var width = rect.width();
                var Xpos=event.clientX;
                if (Xpos<left)
                    rect.css({"background":"red"});
                  else
                  if (Xpos>left+width)
                      rect.css({"background":"blue"});
    
            }
        })();
     });
    

    HTML:

    <table>
      <tr>
        <td>Left</td>
        <td id="rect">Center</td>
        <td>Right</td>
      </tr>
    </table>
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 2021-10-28
      相关资源
      最近更新 更多