0

我有一个示例代码:

javascript:

function bootstrap(id) {
   this.id = id;
   this.init = function() {
      document.getElementById(this.id).onmousemove = positionButton;
   }
   function positionButton(e) {
      e = e || window.event;
      var cursor = {x:0, y:0};
      if (e.pageX || e.pageY) {
         cursor.x = e.pageX;
         cursor.y = e.pageY;
      } else {
         cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
         cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
      }
      var elem = document.getElementById(this.id);
      elem.style.position = 'absolute';
      elem.style.top = cursor.y - 10 + 'px';
      elem.style.left = cursor.x - 30 + 'px';
   }
}

在 html 中:

<div id="button" style="position: absolute; opacity: 1; z-index: 100; width:27px; height:20px; overflow:hidden">
test test
</div>
<script type="text/javascript" src="script.js"></script>
<script>
var bootstrap = new bootstrap('button');
bootstrap.init();
</script>

当我运行代码时,结果没有运行事件 mousemove,如何解决?

4

2 回答 2

0

按钮的样式。你的代码:

width:27px;height:20px;

我改为

width:60px;height:50px;

我在 IE9 上试了一下,效果很好。

于 2012-11-15T03:41:47.707 回答
0

运行我通过稍微修改您的代码创建的这个jsFiddle :

    function bootstrap(id) {
        this.id = id;
        this.init = function() {
            document.getElementById(this.id).onmousemove = positionButton;
        };

        function positionButton(e) {
            e = e || window.event;
            var cursor = {
                x: 0,
                y: 0
            };
            if (e.pageX || e.pageY) {
                cursor.x = e.pageX;
                cursor.y = e.pageY;
            } else {
                cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
                cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
            }
            var elem = document.getElementById(this.id);
            elem.style.position = 'absolute';
            elem.style.top = cursor.y - 10 + 'px';
            elem.style.left = cursor.x - 30 + 'px';
        }
    }

var bootstrap = new bootstrap('button');
bootstrap.init();​

它适用于 Chrome、Safari 和 FFX。

您的浏览器控制台有任何错误吗?

script.js 是否正确下载?

你使用的是什么浏览器?

于 2012-11-15T03:47:20.797 回答