JavaScript游标表现奇怪

时间:2011-06-11 04:14:19

标签: javascript cross-browser cursor

设置


我正在创建一个HTML页面,用div元素替换游标。 Javascript在下面。 div元素只是<div id="cursor"/>

function fixCursor()
{
  var cPos = getCursorPosition();
  cursor.style="top:" + (cPos.y) + "; left:" + (cPos.x) + "; position:fixed; width:16px; height:16px; background-color:#DDDDDD; box-shadow: 2px 2px 4px rgba(0,0,0,.5); border:2px solid #111111; border-radius:0 100% 100% 100%;";
  return;
}

function getCursorPosition(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 if (e.screenX || e.ecreenY) {
        cursor.x = e.screenX;
        cursor.y = e.screenY;
    }
    else if (e.x || e.y) {
        cursor.x = e.x;
        cursor.y = e.y;
    }
    else if (e.clientX || e.clientY) {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX;
        cursor.y = e.clientY;
    }
    return cursor;
}

问题


这仅适用于Opera,并显示在IE上工作的迹象,但不显示光标。在Firefox和Chrome上,没有任何内容。我没有尝试Safari,因为我刚刚卸载它,但根据我的经验,它的渲染工作很像Chrome,无论如何。

3 个答案:

答案 0 :(得分:0)

您可以将custom cursors添加到CSS cursor属性,将所有主要浏览器添加到Opera support it中。如果你希望它在IE中工作,你需要使用.cur或.ani光标文件,其他浏览器至少支持.cur,.png,.jpg和.gif。

或者this answer指向jQuery plugin,可能比自己实施更容易使用。

就我个人而言,我从未发现我 使用自定义光标的情况,我通常只在样式表中使用.png cursor并为其保留合理的默认值不支持.png游标的浏览器。

答案 1 :(得分:0)

在您的代码中,getCursorPosition会获取一个事件对象e。在fixCursor中,您没有传递任何内容。您应该让fixCursor同时获取一个事件对象并将其传递给getCursorPosition。然后,在您可能调用fixCursor的事件处理程序中,传入传递给事件处理程序的事件对象。

此外,您不能将style设置为等于字符串。但是,您可以设置style.cssText

答案 2 :(得分:0)

你打算在早上做这件事吗?那是开销的很多。在任何情况下,我都会看到一些问题,但我不知道是否单独修复它们会为您提供跨浏览器解决方案。

首先,我们假设您正在触发此函数onmousemove,所以您在脚本中有这个:

document.onmousemove = fixCursor;

你必须让fixCursor()将事件对象传递给getCursorPosition(),如下所示:

function fixCursor(e)
{
  var cPos = getCursorPosition(e);
...

您必须明确设置每个样式属性:

cursor.style.cursor = 'none'; // Didn't see you set this
cursor.style.top = cPos.y;
cursor.style.left = cPos.x;
cursor.style.position = "fixed";

快速测试显示,这适用于Firefox但不适用于IE。将位置设置为“绝对”在IE中更接近,但不是有用的。

编辑:哦,看来你没有正确引用你的fixCursor()函数中的“cursor”div。使用

var cursor = document.getElementById('cursor');