


How to use CSS to achieve mouse movement control page element effects? (code example)
This article will introduce to you how to use the mouse position mapped by CSS to control the effect of page elements through mouse movement. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Map the mouse position or implement a drag and drop effect, we can do this inJavaScript
. But in fact, there is a simpler way in CSS, and we can still achieve the same functionality without usingJavaScript
!
You can imitate the mouse "click and drag" effect using only CSS. Let's take a look at how to get the user's mouse position and map it to a CSS
custom property: --positionX
and --positionY
. The following are the specific implementation steps.
Initialization
Our first demo
will use --positionX
and --positionY
custom properties to Set the width and height of the element.
<div> <div></div> </div>
*, *::before, *::after { padding: 0; margin: 0 auto; box-sizing: border-box; } body { background-color: black; height: 100vh; } .content { --positionX: 0; --positionY: 0; position: absolute; top: 0; right: 0; bottom: 0; left: 0; display: flex; justify-content: center; align-items: center; } .square { width: 100px; height: 100px; background: white; }
This is our initial state. We have a container named .content
here <div>. Its width and height are filled with <code>body
, which is the content body of the project. . The <div> with the class name <code>.square
is the element we want to control with the mouse in this example.
We also added two custom attributes to the content. We'll use the mouse position to set the values of these properties, and then use them to set the width and height of the .square
element.
Once we draw custom properties for the mouse position, we can use them to do almost anything we want. For example, we can use them to set the top/left
of an absolutely positioned element, control the transform
attribute, set the background-position
, adjust the color
, even set the content of pseudo elements, etc. We will see some such demonstration effects and corresponding Codepen
project links at the end of the article.
grid Grid
The goal is to create an invisible grid on the screen and use the :hover
pseudo-class to map each "cell" to our A set of values for a custom property. At this point, when the mouse cursor moves to the right side of the screen, the value of --positionX
will be higher: when the mouse moves to the left, it becomes lower. The same goes for --positionY
: when the cursor moves to the top, the value will be lower, and when the cursor moves to the bottom, the value will be higher.
Something to note about grid size and grid tiles: We can actually make any grid size we can achieve. The larger it is, the more accurate the custom property value will be. But this also means that we will have more grid tiles. Too many grid tiles may cause performance issues. It is very important to adjust the grid size to maintain the appropriate balance according to the actual project.
Now, let's say we need a 10×10 grid, so a total of 100 grid tiles in our container. (In actual development, you can use syntax such as pug to quickly create tables. In the example, all 100 spaces are represented by div
)
<div> <div></div> </div>
Due to the cascading relationship, .cell The
element is placed before the .content
element.
We hope to use the .cell
class to control .square
. Due to the cascading relationship of CSS, an element can only control its child elements (or the child element) and the sibling element (or child element of a sibling element) located behind it
This means two things:
- Each
.cell
must precede the element that needs to be controlled (.square
in this example). - We cannot put these
.cell
in a container. If we do this, the.content
elements will no longer be their sibling elements.
Positioning cells
There are many ways to locate .cells
. For example, we can use position: absolute
and set their top
and left
properties; or we can also use transform
to transform the position ;But the easiest option is actually to use display: grid
.
body { background-color: #000; height: 100vh; display: grid; grid-template: repeat(10, 1fr) / repeat(10, 1fr); } .cell { width: 100%; height: 100%; border: 1px solid gray; z-index: 2; }
border
Just temporary, under development so we can see the grid on screen, will remove it later. z-index
is very important because we want the cell to appear on top of the content.
Here's what we've done so far:
<div> <div></div> </div>
*, *::before, *::after { padding: 0; margin: 0 auto; box-sizing: border-box; } body { background-color: black; height: 100vh; display: grid; grid-template: repeat(10, 1fr) / repeat(10, 1fr); } .cell { width: 100%; height: 100%; border: 1px solid gray; z-index: 2; } .content { --positionX: 0; --positionY: 0; position: absolute; top: 0; right: 0; bottom: 0; left: 0; display: flex; justify-content: center; align-items: center; } .square { width: 100px; height: 100px; background: white; }
Add value
We want to do it via .cell
Set the values of --positionX
and --positionY
.
当我们 hover
悬停在第一个(左列).cell
上时,--positionX
值应为 0
。当我们悬停在第二列中的 .cell
上时,值应为 1
。第三 2
,等等。
y轴
也是如此。当我们悬停在第一行(顶部).cell
上时,--positionY
应该为 0
,当我们悬停在第二行的单元格上时,值应该是 1
,等等。
从左到右按顺序排列着白色边框和数字的黑色十乘十方格。
图像中的数字表示网格中每个单元格的编号。如果以一个单一的 .cell
为例——42号单元格——我们可以使用 :nth-child()
来选择它:
.cell:nth-child(42) { }
但我们需要记住几件事:
- 我们只希望此选择器只在
hover
悬停在单元格上时生效,因此我们需要给它附件:hover
。 - 我们希望选择的是
.content
元素而不是单元格本身,因此需要使用一般兄弟选择器~
来做到这一点。
因此,现在当第42个单元格处于 hover
状态时,要将 --positionX
设置为 1
与--positionY
设置为 3
,需要这样做:
.cell:nth-child(42):hover ~ .content { --positionX: 1; --positionY: 3; }
但是有100个单元格,谁想这样做100次呢!?有几种方法可以使上述操作变得更容易:
使用
Sass
中的@for
循环来遍历所有 100 个单元格,并做一些数学运算,每次遍历设置对应的的--positionX
和--positionY
值。将 x 轴和 y 轴分开,用带有
:nth-child
的功能符号分别选择每行和每列。结合这两种方法,同时使用
Sass
@for
循环和:nth-child
功能符号。
我深思熟虑过什么是最简单最好的方法,虽然所有方法都有优缺点。根据要编写的代码数量、编译代码的质量和数学复杂性方面的考虑,最终我选择了第三种方法。如果你有更好的方法,可以在评论中告诉我。
用 @for
循环设置值
@for $i from 0 to 10 { .cell:nth-child(???):hover ~ .content { --positionX: #{$i}; } .cell:nth-child(???):hover ~ .content { --positionY: #{$i}; } }
这是一个基本循环框架,我们需要循环10次,因为上述构造的网格有10行和10列。将网格分为 x轴
和 y轴
,对每列设置 --positionX
,对每行设置 --positionY
。现在要做的是找到一个合适的数学表达式,填到 ???
处,来进行选择每行和每列。
让我们从 x轴
开始
回到我们上面带有数字的网格图像,我们可以看到 第2列
中所有单元格的数字是 10的倍数加2
。第2列
中的单元格是 10的倍数加3
...
现在,让我们把它转换成 :nth-child
的功能表达式。以下是第2列可以表示为:
:nth-child(10n + 2)
- 10n表示选择每个10的倍数。
- 2 是列号,在我们的循环中,将用
#{$i +1]
替换列号来按顺序重复。
.cell:nth-child(10n + #{$i + 1}):hover ~ .content { --positionX: #{$i}; }
现在让我们处理y轴
再看一遍网格图像,关注 第4行
,网格编号介于 41与50
之间。第5行
的网格编号在 51与60
之间等等。要选择每行,我们需要定义其范围。例如,第四行的范围是:
.cell:nth-child(n + 41):nth-child(-n + 50)
(n + 41)
是范围的开始。(-n + 50)
是范围的结尾。
现在,我们用 $i值
的来代替数学公式中的数字。对于范围的开始,得到 (n + #{10 * $i + 1})
,对于范围结尾获得 (-n + #{10 * ($i + 1)})
。
因此,最终的 @for
循环是:
@for $i from 0 to 10 { .cell:nth-child(10n + #{$i + 1}):hover ~ .content { --positionX: #{$i}; } .cell:nth-child(n + #{10 * $i + 1}):nth-child(-n + #{10 * ($i + 1)}):hover ~ .content { --positionY: #{$i}; } }
映射完成!当我们悬停在元素上时,--positionX
和 --positionY
的值会根据鼠标位置而变化。这意味着我们可以使用它们来控制内容中的元素。
处理自定义属性
好了,现在我们已经把鼠标位置映射到两个自定义属性,接下来的事情是使用它们来控制 .square
元素的宽度和高度值。
让我们从宽度开始,假设我们希望 .square
元素的的最小宽度为 100px
(即当鼠标光标位于屏幕左侧时),我们还希望鼠标光标向右移动的每一步都增长 20px
。
使用 calc()
,就可以实现:
.square { width: calc(100px + var(--positionX) * 20px); }
对于高度我们做同样的操作,但用 --positionY
代替:
.square { width: calc(100px + var(--positionX) * 20px); height: calc(100px + var(--positionY) * 20px); }
就是这样!现在我们有一个简单的 .square
元素,宽度和高度由鼠标位置控制。将鼠标光标在界面移动,查看正方形的宽度和高度如何相应地变化,下面是整个示例的完整代码。
<div> <div></div> </div>
*, *::before, *::after { padding: 0; margin: 0 auto; box-sizing: border-box; } body { background-color: black; height: 100vh; display: grid; grid-template: repeat(10, 1fr) / repeat(10, 1fr); } .cell { width: 100%; height: 100%; // border: 1px solid gray; z-index: 2; } @for $i from 0 to 10 { .cell:nth-child(10n + #{$i + 1}):hover ~ .content { --positionX: #{$i}; } .cell:nth-child(n + #{10 * $i + 1}):nth-child(-n + #{10 * ($i + 1)}):hover ~ .content { --positionY: #{$i}; } } .content { --positionX: 0; --positionY: 0; position: absolute; top: 0; right: 0; bottom: 0; left: 0; display: flex; justify-content: center; align-items: center; } .square { width: calc(100px + var(--positionX) * 20px); height: calc(100px + var(--positionY) * 20px); background: white; transition: all 0.3s; }
我添加了一个小的过渡效果,看起来更顺畅。当然,这不是必须的。我也注释了 .cell
元素的的 border
。
让我们尝试一种替代方法
可能会有一种情况,即您想要"绕过" --positionX
和 --positionY
,并将最终值直接设置在 @for循环
中。对于我们的例子而言,可以像下面这样实现:
@for $i from 0 to 10 { .cell:nth-child(10n + #{$i + 1}):hover ~ .content { --squareWidth: #{100 + $i * 20}px; } .cell:nth-child(n + #{10 * $i + 1}):nth-child(-n + #{10 * ($i + 1)}):hover ~ .content { --squareHeight: #{100 + $i * 20}px;: #{$i}; } }
.square
元素从而可以这样自定义属性:
.square { width: var(--squareWidth); height: var(--squareHeight); }
这种方法相比较而言更灵活一些,因为它允许更高级的 Sass
数学(和字符串)函数,但它的主要原理与我们示例的内容是完全相同的。
接下来呢?
好吧,剩下的就由你决定如何使用——而且可能性是无穷无尽的!你能在 CSS
中更进一步地使用映射鼠标位置地技巧吗?下面是几个页面图形会随着鼠标变换的例子:
-
跳动粒子
演示地址:https://codepen.io/amit_sheen/pen/c402584728a49c435fefa388e1692687
-
3D文字
演示地址:https://codepen.io/amit_sheen/pen/261df6f09d15a179b63454bb75acc191
-
透视图像
演示地址:https://codepen.io/amit_sheen/pen/7ec61599091d3be99d503634b1b7e884
-
打字机效果
、
演示地址:https://codepen.io/amit_sheen/pen/af022e80f75789c6b80a8d0eb718f890
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of How to use CSS to achieve mouse movement control page element effects? (code example). For more information, please follow other related articles on the PHP Chinese website!

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more.

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

Article discusses CSS Flexbox, a layout method for efficient alignment and distribution of space in responsive designs. It explains Flexbox usage, compares it with CSS Grid, and details browser support.

The article discusses techniques for creating responsive websites using CSS, including viewport meta tags, flexible grids, fluid media, media queries, and relative units. It also covers using CSS Grid and Flexbox together and recommends CSS framework

The article discusses the CSS box-sizing property, which controls how element dimensions are calculated. It explains values like content-box, border-box, and padding-box, and their impact on layout design and form alignment.

Article discusses creating animations using CSS, key properties, and combining with JavaScript. Main issue is browser compatibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
