gpt4 book ai didi

javascript - 将鼠标移到另一个div中的另一个元素上时如何更改div样式?

转载 作者:行者123 更新时间:2023-11-27 23:18:13 24 4
gpt4 key购买 nike

我正在处理我的个人元素,当我将光标悬停在另一个 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

最佳答案

您需要在 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";
});

此时您可能已经意识到光标没有以鼠标为中心,因此在 .cursor CSS 标记内添加此行来解决此问题:

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

Codepen version

关于javascript - 将鼠标移到另一个div中的另一个元素上时如何更改div样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58157588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com