更改指针光标的CSS URL(使用Javascript)

时间:2017-04-14 10:54:29

标签: javascript css cursor

昨天我问了一个问题here关于使用javascript定期更改光标,让它看起来像动画一样。我得到了一个很好的答案(谢谢湿婆!)。我现在一直试图让两个不同的动画'游标,一个用于'汽车'光标,以及指针的另一个指针'光标。

我尝试了很多不同的方法,但只是无法解决(我必须承认,我对此完全陌生 - 试图改进)。这是我尝试这样做的方法之一:

<!DOCTYPE html>
<html>
<head>

<script type = "text/javascript">   
var images = [
'assets/shared/cursors/drum1.cur',
'assets/shared/cursors/drum2.cur',
'assets/shared/cursors/drum3.cur',
'assets/shared/cursors/drum4.cur'
];

var x = 0;

function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor = 'url("' + images[x] + '"), default';
} 

setInterval(displayNextImage, 250);
</script>

<script type = "text/javascript">   
var images = [
'assets/shared/cursors/point1.cur',
'assets/shared/cursors/point2.cur',
'assets/shared/cursors/point3.cur',
'assets/shared/cursors/point4.cur'
];

var x = 0;

function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor:pointer = 'url("' + images[x] + '"), default';
} 

setInterval(displayNextImage, 250);
</script>

<body>

<div style="height: 1000vh; width: 1000vw;"></div>
</body>
</html>
</head>
</html>

如果可能,我想在没有jQuery的情况下这样做。

同样,任何帮助都非常感谢。

谢谢! :)

1 个答案:

答案 0 :(得分:0)

您可以尝试使用jQuery:

var images = [
  'assets/shared/cursors/point1.cur',
  'assets/shared/cursors/point2.cur',
  'assets/shared/cursors/point3.cur',
  'assets/shared/cursors/point4.cur'
];

var x = 0;

function changeLinkCursorHoverBinding(){
  $("a").hover(function(){/*this is the mouseenter triggered function*/
    $(this).css("cursor",'url("' + images[x] + '"), default');
  }, function(){
    //handle mouseleave here if needed
  });

  x = (x === images.length - 1) ? 0 : x + 1;//put at the end to start at 0

  setTimeout(changeLinkCursorHoverBinding, 250);
}

$(document).ready(changeLinkCursorHoverBinding);//initial call of the function

修改

或者没有jQuery:

var images = [
  'assets/shared/cursors/point1.cur',
  'assets/shared/cursors/point2.cur',
  'assets/shared/cursors/point3.cur',
  'assets/shared/cursors/point4.cur'
];

var x = 0;

function changeLinkCursorHoverBinding(){
 var elems = document.querySelectorAll("a");
 elems.removeEventListener("mouseenter", onHover);
 elems.removeEventListener("mouseleave", offHover);

 elems.addEventListener("mouseenter", onHover);
 elems.addEventListener("mouseleave", offHover);

 x = (x === images.length - 1) ? 0 : x+1;

 setTimeout(changeLinkCursorHoverBinding, 250);
}

function onHover(){
  var elems = document.querySelectorAll("a");
  for(e in elems){
    e.style.cursor = "url('" + images[x] + "'), default";
  }//you can use the regular for loop here if you wanna
}

function offHover(){
  var elems = document.querySelectorAll("a");
  for(e in elems){
    /*handle mouseleave here*/
  }
}

我必须为EH函数命名(并在每次调用时删除EH)因为我不确定addEventListener是否会覆盖相同的处理程序再次调用。

修改

对于非jQuery方式,您需要以这种方式在onload="changeLinkCursorHoverBinding()"标记上添加<body><body onload="changeLinkCursorHoverBinding()">(页面加载后的初始调用)。