检测相对于元素的鼠标位置

时间:2014-08-25 03:43:17

标签: javascript html css cursor-position

我在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;
} 

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

2 个答案:

答案 0 :(得分:2)

你可以用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/

答案 1 :(得分:0)

你可以试试这个:

 $(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>