一、js完成图片跟随鼠标移动
1、js部分
<script>
var img = document.getElementById('img')
console.log(img);
// 给整个页面绑定事件 document
document.onmousemove = function (event) {
// console.log('测试');
var event = event || window.event
// console.log(event.clientX);
// console.log(img.clientWidth);
img.style.left = event.clientX - img.clientWidth / 2 + 'px'
img.style.top = event.clientY - img.clientHeight / 2 + 'px'
}
</script>
2、样式与body部分
<style>
#img {
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<img src="./image/tianshi.gif" alt="" id="img">
</body>
二、小球跟谁鼠标移动并改色
1、js部分
<script>
var divArr = document.getElementsByTagName('div')
console.log(divArr);
document.onmousemove = function (event) {
var event = event || window.event
var i = 0
// for (var i = 0; i < divArr.length; i++) {
var timer = setInterval(function () {
i++
if (i < divArr.length) {
divArr[i].style.display = 'block'
divArr[i].style.backgroundColor = changColor()
divArr[i].style.left = event.clientX - divArr[i].clientWidth / 2 + 'px'
divArr[i].style.top = event.clientY - divArr[i].clientHeight / 2 + 'px'
} else {
clearInterval(timer)
}
}, 100)
// }
}
</script>
2、读入数据
代码如下(示例):
<style>
div {
position: absolute;
width: 50px;
height: 50px;
/* background-color: yellow; */
border-radius: 50%;
display: none;
}
body {
background-color: black;
background-color: rgb(red, green, blue);
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>