首页 > 解决方案 > 将鼠标移到另一个 div 中的另一个元素上时如何更改 div 样式?

问题描述

我正在处理我的个人项目,当我将它悬停在另一个 div 内的 h1 元素上时,我需要更改作为我的光标的 div 样式(从宽度和高度 10px 到宽度和高度 100px)。

我试过了

h1:hover ~ .cursor{
  width: 100px;
  height: 100px;
}

h1:hover + .cursor{
  width: 100px;
  height: 100px;
}

但在这种情况下它不起作用。你知道怎么做吗?

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
    <header class="mainHeader">
        <h1>WELCOME</h1>
    </header>

    <div class="cursor"></div>

    <script src="js/cursor.js"></script>
</body>
</html>

CSS:

@import url('https://fonts.googleapis.com/css?family=Montserrat:400,700,800&display=swap');

*, html{
    margin: 0;
    font-family: 'Montserrat', sans-serif;
    cursor: none;
}

.mainHeader{
    background: rgb(255, 255, 255);
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

h1{
    color: rgb(255, 255, 255), 255);
    font-weight: 800;
}

.cursor{
    width: 10px;
    height: 10px;
    background: rgb(255, 255, 255);
    position: absolute;
    border-radius: 50%;
    box-sizing: border-box;
    pointer-events: none;
    transition: 200ms ease-out;
    mix-blend-mode: difference;
}

h1:hover ~ .cursor{
    width: 100px;
    height: 100px;
}

这是我负责用鼠标跟随 div 的 js 代码:

const cursor = document.querySelector('.cursor');

document.addEventListener('mousemove', e => {
    cursor.setAttribute("style", "top: " + (e.pageY - 5) + "px; left: " + (e.pageX - 5) + "px;");
});

光标有效,因为当我更改代码以使“〜”有效时,一切正常。我对javascript中的解决方案持开放态度。

Codepen 版本:https ://codepen.io/Flayy/pen/vYBwzgE

标签: javascripthtmlcss

解决方案


您需要在 H1 标签上添加一个类(或一个 id)才能在脚本中选择它,例如:

<h1 class="bigCursor">WELCOME</h1>

在脚本中:

const bigCursor = document.querySelector('.bigCursor')

因此,将您的“mousemove”事件函数更改为更灵活的方式来编辑样式:

document.addEventListener('mousemove', e => {
    cursor.style.top = e.pageY + 'px';
    cursor.style.left = e.pageX + 'px';
});

并将其添加到函数中以分别增加和减少光标的大小

bigCursor.addEventListener('mouseenter', e => {
    cursor.style.width = "100px";
    cursor.style.height = "100px";
});

bigCursor.addEventListener('mouseleave', e => {
    cursor.style.width = "10px";
    cursor.style.height = "10px";
});

此时你可能已经意识到光标不在鼠标的中心,所以在.cursorCSS 标签内添加这一行来解决这个问题:

transform: translate(-50%, -50%);

代码笔版本


推荐阅读