js实现可切换正负极的磁铁相吸相斥动画效果代码

代码语言:html

所属分类:动画

代码描述:js实现可切换正负极的磁铁相吸相斥动画效果代码,点击鼠标左键可切换正负极。

代码标签: js 切换 正负极 磁铁 相吸 相斥 动画

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开


<!DOCTYPE html>
<html lang="en" >

<head>

  <meta charset="UTF-8">
  

  
  <link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Quicksand:wght@700&amp;display=swap'>
  
<style>
:root {
	--polarity: "+";
	--color: red;
}
body {
	height: 100vh;
	margin: 0;
	display: grid;
	place-items: center;
	background-color: #add495;
	font-family: system-ui;
	overflow: hidden;
	user-select: none;
}

.magnet {
	width: 100px;
	aspect-ratio: 1/1;
	background: linear-gradient(to bottom, dimgray 20%, transparent 20%),
		var(--color);
	border-radius: 0 0 50px 50px;
	clip-path: polygon(
		0% 0%,
		33% 0%,
		33% 66%,
		66% 66%,
		66% 0%,
		100% 0%,
		100% 100%,
		0% 100%
	);
	position: absolute;
	z-index: 2;
	transition: .05s;
}
.magnet:after {
	content: var(--polarity);
	width: 100%;
	text-align: center;
	font-size: 36px;
	line-height: 48px;
	font-weight: 900;
	position: absolute;
	left: 0;
	bottom: 0;
}

.metal {
	width: 50px;
	aspect-ratio: 1/1;
	text-align: center;
	line-height: 40px;
	font-size: 36px;
	background: 
		radial-gradient(circle at 66% 33%, transparent, rgba(0,0,0,.5)),
		gray;
	border-radius: 50%;
	position: absolute;
	box-shadow: 0 0 5px rgba(0,0,0,.5);
	transform: translate(-50%,-50%);
	transition: .05s;
}

.negative {
	transform: scaleY(-1);
}
</style>



</head>

<body  >
  Click to change magnet polarity
<div class="magnet negative"></div>

      <script >
const magnet = document.querySelector(".magnet"),
			root = document.documentElement;

var offset = 50,
		ball_count = 100

function addMetalObjects() {
	var m = document.createElement('div')
	m.className = 'metal'
	m.style.left = Math.random()*(window.innerWidth - 25) + 'px'
	m.style.top = Math.random()*(window.innerHeight - 25) + 'px'
	m.innerHTML = '-'
	document.body.appendChild(m)
}

while(document.querySelectorAll('.metal').length < ball_count) {
	addMetalObjects()
}

function rand() {
	return Math.floor(Math.random()*4)
}

function checkPolarity() {
	var balls = document.querySelectorAll('.metal'),
			m_loc = magnet.getBoundingClientRect(),
			r1 = m_loc.width,
			x1 = m_loc.x + r1*.5,
			y1 = m_loc.y + r1*.5

	balls.forEach(function(elm){
		var b_loc = elm.getBoundingClientRect(),
				.........完整代码请登录后点击上方下载按钮下载查看

网友评论0