我想实现一个函数,当将鼠标悬停在图像上时,它将在光标所在的位置打开图像。如何做到这一点?我已经尝试过下面的代码列表,但是它似乎不起作用。它使我的网站无响应。有没有办法使这项工作更正常?
function interval() {
while (true) {
setInterval(showImage, 1);
}
}
function showImage() {
var x = clientX;
var y = clientY;
var image = document.getElementById("image");
image.style.left = x;
image.style.top = y;
}
<a href="#" onmouseover="interval()">THIS IS THE LINK</a>
<div style="display: none;" id="image">
<img src="picture.png" />
</div>
答案 0 :(得分:1)
使图像可见。
仅在指针移动一次后添加侦听器,以免浏览器崩溃。
let attached = false;
let imageContainer = document.querySelector("#image");
const followMouse = (event) => {
imageContainer.style.left = event.x + "px";
imageContainer.style.top = event.y + "px";
}
function showImage() {
if (!attached) {
attached = true;
imageContainer.style.display = "block";
document.addEventListener("pointermove", followMouse);
}
}
function hideImage() {
attached = false;
imageContainer.style.display = "";
document.removeEventListener("pointermove", followMouse);
}
#image {
position: absolute;
display: none;
width: 50px;
height: 50px;
background-color: red;
pointer-events: none;
}
<a href="#" onpointerenter="showImage()" onpointerleave="hideImage()">THIS IS THE LINK</a>
<div id="image">
</div>
答案 1 :(得分:1)
实际上,使用CSS而不是JavaScript会更好,请参见下面的演示
.interval:hover ~ #image {
display: block;
}
.imageParent {
display: none;
}
<a href="#" class="interval">THIS IS THE LINK</a>
<div class="imageParent" id="image">
<img width="200px"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Node.js_logo.svg/1200px-Node.js_logo.svg.png"
/>
</div>
答案 2 :(得分:1)
尝试一下:
#imageContainer {
opacity: 0; # Not visible
}
#linkWithImage:hover ~ #imageContainer {
opacity: 1; # Visible
}
<a id="linkWithImage" href="https://www.breakingbadstore.com/">Link with image</a>
<div id="imageContainer">
<img src="https://gcdn.emol.cl/mitos-y-enigmas/files/2019/09/breaking-bad.jpg" width="500px" />
</div>
答案 3 :(得分:0)
您可以这样做
document.addEventListener("mousemove",function (e) {
var body = document.querySelector('body');
var bubbles = document.createElement("span");
var x = e.offsetX;
var y = e.offsetY;
bubbles.style.left = x+'px';
bubbles.style.top = y+'px';
var size = Math.random() * 100;
bubbles.style.width = 20 + size+'px';
bubbles.style.height = 20 + size+'px';
body.appendChild(bubbles);
setTimeout(function () {
bubbles.remove();
},4000)
})
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
overflow: hidden;
height: 100vh;
}
span{
position: absolute;
background: url(https://www.imgworlds.com/wp-content/uploads/2015/12/18-CONTACTUS-HEADER.jpg);
background-size: cover;
pointer-events: none;
transform: translate(-50%, -50%);
animation: animate 10s linear infinite;
}
@keyframes animate{
0%{
transform: translate(-50%, -50%);
opacity: 1;
}
100%{
transform: translate(-50%, -1000%);
opacity: 0;
}
}