使用Javascript

时间:2017-04-13 13:50:26

标签: javascript css cursor

我目前正在更新我的网站。我想在其中一个页面上有一个动画光标。我发现现代浏览器不支持.ani格式或GIF动画,所以我认为我可以将.ani格式用于旧浏览器,而现代浏览器有一个使用javascript更改的.png游标

这是我尝试的内容:

<!DOCTYPE html>
<html>
<head>

<body background="example.gif">

<style type="text/css" id="cursor"> body {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;} </style>

<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("cursor") .body images[x];
}

function startTimer() {
setInterval(displayNextImage, 400);
}

var images = [], x = -1;
images[0] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum1.png'), default;};
images[1] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum2.png'), default;};
images[2] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;};
</script>


<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("test") .src = images[x];
}

function startTimer() {
setInterval(displayNextImage, 400);
}

var images = [], x = -1;
images[0] = "assets/shared/cursors/drum1.png";
images[1] = "assets/shared/cursors/drum2.png";
images[2] = "assets/shared/cursors/drum3.png";
</script>

</head>

<body onload="startTimer()">

<img id=test src="assets/shared/cursors/drum3.png">

<div style="height: 1000px; width: 1000px;"></div>

</body>
</html>

我把测试&#39;图像进入以查看代码是否完全有效,并且确定&#39;测试&#39;图像确实按计划发生了变化,但光标只停留在&#39; drum3.png&#39;而不是改变。我尝试了很多不同的方法,但无法让它发挥作用。

如果可能,我想避免使用JQuery。

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

var images = [
  'http://lorempixel.com/21/21/',
  'http://lorempixel.com/22/22/',
  'http://lorempixel.com/23/23/'
];

var x = 0;

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

setInterval(displayNextImage, 400);
html, body {
  height: 100%;
}

body {
  cursor: url('http://lorempixel.com/20/20/'), default;
}

答案 1 :(得分:0)

我无法弄清楚如何使用.ani后备光标,所以我将.png文件更改为.cur文件,这些文件适用于新旧浏览器。所以,代码最终看起来像这样:

    <!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>

<body>

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

再次感谢湿婆。没有你,我无法解决这个问题。

我在这里问过一个相关但不同的问题:Changing CSS URL for pointer cursor (using Javascript)