简体   繁体   English

跟随已经动画元素的动画光标

[英]Animate cursor following already animated element

I have an element which has an animation for scaling up and down (like breathing effect) and I want to add cursor following.我有一个元素,它有一个用于放大和缩小的动画(如呼吸效果),我想添加光标跟随。

My code works only If I delete the animation in CSS.我的代码只有在我删除 CSS 中的动画时才有效。

What I'm doing wrong?我做错了什么?

looks like your post is mostly code;看起来你的帖子主要是代码; please add some more details.请添加更多详细信息。

 class FollowCursor { constructor(element, window) { this.element = element; this.w = window; this.w.onmousemove = this.move.bind(this); } move(e) { this.element.setAttribute( "style", `transform: translate(${e.clientX}px, ${e.clientY}px);` ); } } const el = document.querySelector(".el") const cursorFollowing = new FollowCursor(el, window)
 .el { position: absolute; animation: a-breathing 8s infinite forwards; left: 0; top: 0; width: 30px; height: 30px; background-color: yellow; } div { position: relative } @keyframes a-breathing { 0% { transform: scale(1); } 60% { transform: scale(1.8); } 100% { transform: scale(1); } } ```
 <div> <div class="el"> </div> </div>

jsfiddle snippet jsfiddle 片段

I believe you'll get your expected behavior if you change this line如果您更改此行,我相信您会得到预期的行为

transform: translate(${e.clientX}px, ${e.clientY}px);

for this:为了这:

position: absolute; top: ${e.clientY}px; left: ${e.clientX}px

Eg: https://jsfiddle.net/cxszqdka/例如: https : //jsfiddle.net/cxszqdka/

You're overwriting your transform attribute since you can only have one per element, so you need an element to move around and another div element to do the breathing;您正在覆盖您的 transform 属性,因为每个元素只能有一个,因此您需要一个元素移动,另一个 div 元素进行呼吸; here is the solution:这是解决方案:

 class FollowCursor { constructor(element, window) { this.element = element; this.w = window; this.w.onmousemove = this.move.bind(this); } move(e) { this.element.setAttribute( "style", `transform: translate(${e.clientX}px, ${e.clientY}px);` ); } } const el = document.querySelector(".el") const cursorFollowing = new FollowCursor(el, window)
 .el { position: absolute; left: 0; top: 0; width: 30px; height: 30px; background-color: yellow; } .breathing-element { animation: a-breathing 8s infinite forwards; width: 100%; height: 100%; background: red; } div { position: relative } @keyframes a-breathing { 0% { transform: scale(1); } 60% { transform: scale(1.8); } 100% { transform: scale(1); } }
 <div> <div class="el"> <div class="breathing-element"></div> </div> </div>

You can also combine multiple values for the transform attribute following this pattern:您还可以按照以下模式组合转换属性的多个值:

transform: translate | transform | scale | rotate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM