1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 原生js实现鼠标点击出现文字特效(颜色随机)!

原生js实现鼠标点击出现文字特效(颜色随机)!

时间:2020-04-28 17:27:11

相关推荐

原生js实现鼠标点击出现文字特效(颜色随机)!

可供参考,可直接通过链接引用!

以下是js文件:

window.onload = function() {//定义点击出现文字类function ClickFrontShow() {//定义所需文字和颜色this.fron = ['高兴', '开心', '❤', '欢乐', '愉悦', '愉快', '快乐', '欢喜', '喜悦', '欢欣', '欢畅', '欢腾', '雀跃', '欢快'];this.colo = ['#FF69B4', '#ff6651', 'orange', '#FF00FF', '#00FF7F', '#00BFFF', '#BA55D3'];//获取body元素this.elBody = document.getElementsByTagName("body")[0];//初始化randomNumthis.randomNum = null;//初始化字体indethis.finde = 0;//初始化classNamethis.cls = 0;}//定义初始化ClickFrontShow.prototype.init = function(frontArray, colorArray) {//自定义颜色和字体this.fron = frontArray || this.fron;this.colo = colorArray || this.colo;this.listenMouse();}//创建文字 ClickFrontShow.prototype.createFront = function (classname) {var self = this;let ospan = document.createElement('span');//设置样式let cssText = "position:absolute; width: 40px; height: 20px; cursor: default; transform: translate(-50%,-50%); font-weight: bold; opacity: 1; z-index: 1000; transition: 1s;";//随机字体和颜色let randomFront = self.fron[self.finde];let randomColor = self.colo[Math.round(Math.random()*(self.colo.length-1))];//字体下标增1self.finde = (self.finde+1) % self.fron.length;//向body中添加元素self.elBody.appendChild(ospan);//绑定一个classnameospan.className = String(classname);//添加样式ospan.style.cssText = cssText + "-moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;user-select: none;"ospan.style.color = randomColor;ospan.innerHTML = randomFront;}//监听鼠标点击ClickFrontShow.prototype.listenMouse = function() {var self = this;//鼠标点击事件document.onclick = function(e) {//避免classname值重复导致出现bugif(self.cls === 20){self.cls = 0;}else{self.cls += 1;}//创建文字self.createFront(self.cls);let el = document.getElementsByClassName(self.cls)[0];//鼠标点击位置el.style.left = e.clientX + 'px';el.style.top = e.clientY + 'px';//过时改变setTimeout(function() {el.style.opacity = 0;el.style.top = el.offsetTop - 100 + 'px';}, 100);//过时清除setTimeout(function() {self.elBody.removeChild(el);}, 2000);}}//实例化var frontShow = new ClickFrontShow();//用户可在此传递参数,默认第一个参数是字体数组;//第二个参数是颜色数组,必须是数组类型!frontShow.init();}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。