zl程序教程

您现在的位置是:首页 >  前端

当前栏目

使用jQuery实现点击页面时,出现心型特效,几秒后消失的效果案例

jQuery案例 实现 页面 出现 效果 点击 特效
2023-09-14 09:13:55 时间

首先呢,实现这个特效使用的技术是前端技术jQuery,实现代码只需几十行即可。

第一步创建一个demo.html文件,给body设置一个高度,这里如果body如果没有设置高度的话,不会看到效果。

html页面创建完成之后,写入如下代码:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>心型特效</title>
	<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
	<script>
		$(function(){
			$("body").click(function(e){
				// 创建div父元素
				var parentDiv = $("<div></div>");
				// 设置属性
				parentDiv.css({
					"width":"20px",
					"height":"20px",
					"position":"absolute",
					"z-index":"10000"
				});
				// 创建一个div容器元素
				var conDiv = $("<div></div>");
				conDiv.css({
					"width":"100%",
					"height":"100%",
					"position":"relative"
				});
				// 将容器元素添加到父元素中
				parentDiv.append(conDiv);
				// 创建子元素
				var childDiv = conDiv.append("<div></div><div></div><div></div>");
				var divs = conDiv.children();
				// 设置颜色随机
				var color = "rgb("+parseInt(Math.random()*250+5)
							+","+parseInt(Math.random()*250+5)
							+","+parseInt(Math.random()*250+5)+")";
				// 设置子元素属性
				$(divs[0]).css({
					"width":"60%",
					"height":"60%",
					"background-color":color,
					"border-radius":"100%"
				});
				$(divs[1]).css({
					"width":"60%",
					"height":"60%",
					"background-color":color,
					"border-radius":"100%",
					"position":"absolute",
					"top":"0",
					"right":"0"
				});
				$(divs[2]).css({
					"width":"60%",
					"height":"60%",
					"background-color":color,
					"position":"absolute",
					"top":"20%",
					"left":"20%",
					"transform":"rotate(45deg)",
					"-ms-transform":"rotate(45deg)",
					"-webkit-transform":"rotate(45deg)"
				});
				// 通过事件对象获取鼠标坐标
				var x = e.pageX;
				var y = e.pageY;
				// 修改div父元素位置
				parentDiv.css({"left":x+"px","top":y+"px"});
				// 添加到body中
				$("body").append(parentDiv);
				// 2秒后消失
				parentDiv.animate({
					"width":"25px",
					"height":"25px",
					"top":(y-200)+"px",
					"opacity":0
				},2000,function(){
					parentDiv.remove();
				});
			});
		});
	</script>
</head>
<body style="height:800px;background-color:#CBE8F0;">
	
</body>
</html>

代码编写完成,通过浏览器打开该文件,即可看到如下效果:

以上就完成了鼠标点击页面时,出现心型特效的效果了。