天地图模仿高德图标跳动效果AMAP_ANIMATION_BOUNCE

			// applyBounceAnimation 函数,用于给指定元素应用弹跳动画
			applyBounceAnimation(element) {
			    // 获取元素的当前 transform 属性
			    const currentTransform = window.getComputedStyle(element).transform;
				console.log('currentTransform',currentTransform);
			
			    // 提取现有的 translate3d 值
			    const regex = /matrix3d\(([^)]+)\)/;
			    const match3d = currentTransform.match(regex);
				
				// 声明变量在外部作用域
				let translateX = '0px';
				let translateY = '0px';
				let translateZ = '0px';
				if (match3d) {
					// 如果是 matrix3d 格式的 transform
					const transformValues = match3d[1].split(', ');
					translateX = transformValues[12];
					translateY = transformValues[13];
					translateZ = transformValues[14];
			
					console.log(translateX, translateY, translateZ);
				} else {
					// 可能是 2D 矩阵
					const matrixRegex = /matrix\(([^)]+)\)/;
					const match = currentTransform.match(matrixRegex);
					
					if (match) {
						const matrixValues = match[1].split(', ');
						translateX = matrixValues[4];
						translateY = matrixValues[5];
						console.log(translateX, translateY, 'No Z value for 2D');
					}
				}
			
			    // 随机动画名称
				const animationName = 'bounce-' + Math.random().toString(36).substr(2, 9); 
				// 创建通用的 @keyframes 动画
				const keyframes = `
					@keyframes ${animationName} {
						0% {
							transform: translate3d(${translateX}px, ${translateY}px, ${translateZ});
						}
						100% {
							transform: translate3d(${translateX}px, ${parseFloat(translateY) - 50}px, ${translateZ});
						}
					}
				`;
				console.log('charu',keyframes);
		
				// 插入到样式表中,只插入一次
				const styleSheet = document.styleSheets[0];
				console.log('styleSheet',styleSheet);
				const existingRule = Array.from(styleSheet.cssRules).some(rule => rule.name === 'bounce-animation');
				if (!existingRule) {
					console.log("插入css")
					styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
					console.log(styleSheet.cssRules); // 查看插入后的所有规则
				}
		
				// 确保样式插入后重新渲染
				requestAnimationFrame(() => {
					// 给元素添加动画
					element.style.animation = `${animationName} 0.5s infinite ease-in-out alternate`;
					// 当动画结束时,移除动画并继续到下一个元素
					setTimeout(()=>{
						element.style.animation = '';
					},10000)
				});
			    
			}

通过编写方法,实现传入图标元素dom来实现动态更新css样式,来完成跳动动画效果

你可能感兴趣的:(javascript)