javascript - 将鼠标移到另一个 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
解决方案
您需要在 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%);
推荐阅读
- php - phpredis 会话锁定 -- 未能获得锁定会引发 php 通知 -- 会出现致命错误
- highcharts - 如何隐藏/显示系列中的数据?(高图)
- html - IFrame 在 IE 和 Firefox 中显示空白/空内容——
- python - 如何根据类别设置不同情节的图例?
- typescript - Openlayers:LineString 上的渐变发光
- ios - mp3 无法在 ios 上播放
- python - Python数组对齐总是相同的输出,即使输入不同
- sql-server - 带有子元素的 CDATA
- django - 如何使用 ModelForm 更新具有唯一约束的 Django 模型数据?
- angular - Angular Firebase 注册问题