HTML反向跟随鼠标的动态元素(动态背景)

warning: 这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。

设计JavaScript对css的控制和JavaScript事件。
JavaScript

window.onload = () => {
let N = 0.3;
let div = document.getElementById("myDiv");
let img = document.getElementById("img1");
div.addEventListener("mouseenter", (enter) => {
    let XI = enter.clientX
    div.addEventListener("mousemove", (event) => {
        let X = event.clientX;
        if (X > XI) {
            let K = (X - XI) * N;
            img.style.left = -${K}px;
        }else if ( X < XI) {
            let F = (XI - X) * N;
            img.style.left = ${F}px;
        }
    });
    div.addEventListener("mouseleave", () => {
        img.style.left = "0px";
    });
});}


CSS

body{
    margin: 0px;
    padding: 0px;
}

#myDiv{
    position: relative;
    margin: 0px;
    padding: 0px;
    width: 100%;
    height: 200px;
    background-color: aqua;
}

#img1{
    position: relative;
    object-fit: contain;
    height: 100%;
    width: 100%;
}

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo2</title>
    <link rel="stylesheet" href="./style.css">
    <script src="./script.js"></script>
</head>
<body>
    <div id="myDiv">
        f
    </div>
</body>
</html>
none
最后修改于:2021年11月08日 23:01

添加新评论

召唤看板娘