wow.js使用和动画只执行一次问题优化

 wow.js配合第三方动画库可以让元素出现在屏幕时执行相关的动画

  1. wow.js依赖于animate.css,首先在头部引用animate.css或者animate.min.css。
  2. 在最底部或引入的css下面引用wow.js或者wow.min.js
  3. 使用规则直接查看官网:wow.js — Reveal Animations When Scrolling

问题:wow.js动画官网的代码默认只会执行一次,而有的时候我们想控制某些元素在滚动条滚动时只要该元素出现在屏幕上就执行对应的动画。我们需对源码的scrollCallback函数进行一定的改造即可:

<div class="example-box wow fadeInUp" data-wow-infinite="true"><p>执行动画的元素,必须有class="wow 某个动画名称类"</p><p>data-wow-infinite="true" 加上该属性并将值设为true,则每次元素进入屏幕就会执行一次动画</p><p>data-wow-infinite="false" 不加或者值设为false的话只会在初次进入屏幕时执行一次动画</p>
</div>
//滚动后的回调函数
scrollCallback() {if (this.scrolled) {this.scrolled = false;const results = [];for (let i = 0; i < this.boxes.length; i++) {const box = this.boxes[i];if (box) {const infinite = box.getAttribute('data-wow-infinite');if (this.isVisible(box)) {this.show(box);if (!infinite) continue;} else {if (infinite) this.customStyle(box, true)}results.push(box);}}this.boxes = results;if (!this.boxes.length && !this.config.live) {this.stop();}}
}

//wow.js优化后的源码
function isIn(needle, haystack) {return haystack.indexOf(needle) >= 0;
}function extend(custom, defaults) {for (const key in defaults) {if (custom[key] == null) {const value = defaults[key];custom[key] = value;}}return custom;
}function isMobile(agent) {return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(agent);
}function createEvent(event, bubble = false, cancel = false, detail = null) {let customEvent;if (document.createEvent != null) { // W3C DOMcustomEvent = document.createEvent('CustomEvent');customEvent.initCustomEvent(event, bubble, cancel, detail);} else if (document.createEventObject != null) { // IE DOM < 9customEvent = document.createEventObject();customEvent.eventType = event;} else {customEvent.eventName = event;}return customEvent;
}function emitEvent(elem, event) {if (elem.dispatchEvent != null) { // W3C DOMelem.dispatchEvent(event);} else if (event in (elem != null)) {elem[event]();} else if (`on${event}` in (elem != null)) {elem[`on${event}`]();}
}function addEvent(elem, event, fn) {if (elem.addEventListener != null) { // W3C DOMelem.addEventListener(event, fn, false);} else if (elem.attachEvent != null) { // IE DOMelem.attachEvent(`on${event}`, fn);} else { // fallbackelem[event] = fn;}
}function removeEvent(elem, event, fn) {if (elem.removeEventListener != null) { // W3C DOMelem.removeEventListener(event, fn, false);} else if (elem.detachEvent != null) { // IE DOMelem.detachEvent(`on${event}`, fn);} else { // fallbackdelete elem[event];}
}function getInnerHeight() {if ('innerHeight' in window) {return window.innerHeight;}return document.documentElement.clientHeight;
}// Minimalistic WeakMap shim, just in case.
const WeakMap = window.WeakMap || window.MozWeakMap ||class WeakMap {constructor() {this.keys = [];this.values = [];}get(key) {for (let i = 0; i < this.keys.length; i++) {const item = this.keys[i];if (item === key) {return this.values[i];}}return undefined;}set(key, value) {for (let i = 0; i < this.keys.length; i++) {const item = this.keys[i];if (item === key) {this.values[i] = value;return this;}}this.keys.push(key);this.values.push(value);return this;}};// Dummy MutationObserver, to avoid raising exceptions.
const MutationObserver =window.MutationObserver || window.WebkitMutationObserver ||window.MozMutationObserver ||class MutationObserver {constructor() {if (typeof console !== 'undefined' && console !== null) {console.warn('MutationObserver is not supported by your browser.');console.warn('WOW.js cannot detect dom mutations, please call .sync() after loading new content.');}}static notSupported = true;observe() { }};// getComputedStyle shim, from http://stackoverflow.com/a/21797294
const getComputedStyle = window.getComputedStyle ||function getComputedStyle(el) {const getComputedStyleRX = /(\-([a-z]){1})/g;return {getPropertyValue(prop) {if (prop === 'float') { prop = 'styleFloat'; }if (getComputedStyleRX.test(prop)) {prop.replace(getComputedStyleRX, (_, _char) => _char.toUpperCase());}const { currentStyle } = el;return (currentStyle != null ? currentStyle[prop] : void 0) || null;},};};class WOW {defaults = {boxClass: 'wow',animateClass: 'animated',offset: 0,mobile: true,live: true,callback: null,scrollContainer: null,resetAnimation: true,};constructor(options = {}) {this.start = this.start.bind(this);this.resetAnimation = this.resetAnimation.bind(this);this.scrollHandler = this.scrollHandler.bind(this);this.scrollCallback = this.scrollCallback.bind(this);this.scrolled = true;this.config = extend(options, this.defaults);if (options.scrollContainer != null) {this.config.scrollContainer = document.querySelector(options.scrollContainer);}// Map of elements to animation names:this.animationNameCache = new WeakMap();this.wowEvent = createEvent(this.config.boxClass);}init() {this.element = window.document.documentElement;if (isIn(document.readyState, ['interactive', 'complete'])) {this.start();} else {addEvent(document, 'DOMContentLoaded', this.start);}this.finished = [];}start() {this.stopped = false;this.boxes = [].slice.call(this.element.querySelectorAll(`.${this.config.boxClass}`));this.all = this.boxes.slice(0);if (this.boxes.length) {if (this.disabled()) {this.resetStyle();} else {for (let i = 0; i < this.boxes.length; i++) {const box = this.boxes[i];this.applyStyle(box, true);}}}if (!this.disabled()) {addEvent(this.config.scrollContainer || window, 'scroll', this.scrollHandler);addEvent(window, 'resize', this.scrollHandler);this.interval = setInterval(this.scrollCallback, 50);}if (this.config.live) {const mut = new MutationObserver(records => {for (let j = 0; j < records.length; j++) {const record = records[j];for (let k = 0; k < record.addedNodes.length; k++) {const node = record.addedNodes[k];this.doSync(node);}}return undefined;});mut.observe(document.body, {childList: true,subtree: true,});}}// unbind the scroll eventstop() {this.stopped = true;removeEvent(this.config.scrollContainer || window, 'scroll', this.scrollHandler);removeEvent(window, 'resize', this.scrollHandler);if (this.interval != null) {clearInterval(this.interval);}}sync() {if (MutationObserver.notSupported) {this.doSync(this.element);}}doSync(element) {if (typeof element === 'undefined' || element === null) { ({ element } = this); }if (element.nodeType !== 1) { return; }element = element.parentNode || element;const iterable = element.querySelectorAll(`.${this.config.boxClass}`);for (let i = 0; i < iterable.length; i++) {const box = iterable[i];if (!isIn(box, this.all)) {this.boxes.push(box);this.all.push(box);if (this.stopped || this.disabled()) {this.resetStyle();} else {this.applyStyle(box, true);}this.scrolled = true;}}}// show box elementshow(box) {this.applyStyle(box);box.className = `${box.className} ${this.config.animateClass}`;if (this.config.callback != null) { this.config.callback(box); }emitEvent(box, this.wowEvent);if (this.config.resetAnimation) {addEvent(box, 'animationend', this.resetAnimation);addEvent(box, 'oanimationend', this.resetAnimation);addEvent(box, 'webkitAnimationEnd', this.resetAnimation);addEvent(box, 'MSAnimationEnd', this.resetAnimation);}return box;}applyStyle(box, hidden) {const duration = box.getAttribute('data-wow-duration');const delay = box.getAttribute('data-wow-delay');const iteration = box.getAttribute('data-wow-iteration');return this.animate(() => this.customStyle(box, hidden, duration, delay, iteration));}animate = (function animateFactory() {if ('requestAnimationFrame' in window) {return callback => window.requestAnimationFrame(callback);}return callback => callback();}());resetStyle() {for (let i = 0; i < this.boxes.length; i++) {const box = this.boxes[i];box.style.visibility = 'visible';}return undefined;}resetAnimation(event) {if (event.type.toLowerCase().indexOf('animationend') >= 0) {const target = event.target || event.srcElement;target.className = target.className.replace(this.config.animateClass, '').trim();}}customStyle(box, hidden, duration, delay, iteration) {if (hidden) { this.cacheAnimationName(box); }box.style.visibility = hidden ? 'hidden' : 'visible';if (duration) { this.vendorSet(box.style, { animationDuration: duration }); }if (delay) { this.vendorSet(box.style, { animationDelay: delay }); }if (iteration) { this.vendorSet(box.style, { animationIterationCount: iteration }); }this.vendorSet(box.style, { animationName: hidden ? 'none' : this.cachedAnimationName(box) });return box;}vendors = ['moz', 'webkit'];vendorSet(elem, properties) {for (const name in properties) {if (properties.hasOwnProperty(name)) {const value = properties[name];elem[`${name}`] = value;for (let i = 0; i < this.vendors.length; i++) {const vendor = this.vendors[i];elem[`${vendor}${name.charAt(0).toUpperCase()}${name.substr(1)}`] = value;}}}}vendorCSS(elem, property) {const style = getComputedStyle(elem);let result = style.getPropertyCSSValue(property);for (let i = 0; i < this.vendors.length; i++) {const vendor = this.vendors[i];result = result || style.getPropertyCSSValue(`-${vendor}-${property}`);}return result;}animationName(box) {let aName;try {aName = this.vendorCSS(box, 'animation-name').cssText;} catch (error) { // Opera, fall back to plain property valueaName = getComputedStyle(box).getPropertyValue('animation-name');}if (aName === 'none') {return '';  // SVG/Firefox, unable to get animation name?}return aName;}cacheAnimationName(box) {// https://bugzilla.mozilla.org/show_bug.cgi?id=921834// box.dataset is not supported for SVG elements in Firefoxreturn this.animationNameCache.set(box, this.animationName(box));}cachedAnimationName(box) {return this.animationNameCache.get(box);}// fast window.scroll callbackscrollHandler() {this.scrolled = true;}scrollCallback() {if (this.scrolled) {this.scrolled = false;const results = [];for (let i = 0; i < this.boxes.length; i++) {const box = this.boxes[i];if (box) {const infinite = box.getAttribute('data-wow-infinite');if (this.isVisible(box)) {this.show(box);if (!infinite) continue;} else {if (infinite) this.customStyle(box, true)}results.push(box);}}this.boxes = results;if (!this.boxes.length && !this.config.live) {this.stop();}}}// Calculate element offset topoffsetTop(element) {// SVG elements don't have an offsetTop in Firefox.// This will use their nearest parent that has an offsetTop.// Also, using ('offsetTop' of element) causes an exception in Firefox.while (element.offsetTop === undefined) {element = element.parentNode;}let top = element.offsetTop;while (element.offsetParent) {element = element.offsetParent;top += element.offsetTop;}return top;}// check if box is visibleisVisible(box) {const offset = box.getAttribute('data-wow-offset') || this.config.offset;const viewTop = (this.config.scrollContainer && this.config.scrollContainer.scrollTop) || window.pageYOffset;const viewBottom =viewTop + Math.min(this.element.clientHeight, getInnerHeight()) - offset;const top = this.offsetTop(box);const bottom = top + box.clientHeight;return top <= viewBottom && bottom >= viewTop;}disabled() {return !this.config.mobile && isMobile(navigator.userAgent);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/60829.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【校招VIP】前端算法考察之排序

考点介绍&#xff1a; 不同的场景中&#xff0c;不同的排序算法执行效率不同。 稳定&#xff1a;冒泡、插入、归并 不稳定&#xff1a;选择、快速、堆排序、希尔排序 『前端算法考察之排序』相关题目及解析内容可点击文章末尾链接查看&#xff01; 一、考点题目 1、使用js实…

EOCR-SE2/EOCRSE2在数控技术行业的应用

EOCR-SE2电动机保护器是施耐德EOCR系列中一款以低成本、高性能著称的产品&#xff0c;其广泛应用于各种机床设备中。 EOCRSE2-05RS品牌&#xff1a;施耐德&#xff0c;产地&#xff1a;韩国益山工厂&#xff0c;型号&#xff1a;EOCR-SE2,电流范围&#xff1a;3-30A&#xff0…

DQL语句的执行顺序

DQL语句的通用结构如下所示 Select 子段列表 From 表名列表 Where 条件列表 Group By 分组子段列表 Having 分组后条件列表 Order By 排序子段列表 Limit 分页参数在执行DQL语句时会有一定的执行顺序&#xff1a; 首先执行From 表名列表操作然后执行where 条件列表来指定查询…

541. 反转字符串 II

541. 反转字符串 II 给定一个字符串 s 和一个整数 k&#xff0c;从字符串开头算起&#xff0c;每计数至 2k 个字符&#xff0c;就反转这 2k 字符中的前 k 个字符。 如果剩余字符少于 k 个&#xff0c;则将剩余字符全部反转。 如果剩余字符小于 2k 但大于或等于 k 个&#xff…

工服穿戴检测算法 工装穿戴识别算法

工服穿戴检测算法 工装穿戴识别算法利用yolo网络模型图像识别技术&#xff0c;工服穿戴检测算法 工装穿戴识别算法可以准确地识别现场人员是否穿戴了正确的工装&#xff0c;包括工作服、安全帽等。一旦检测到未穿戴的情况&#xff0c;将立即发出警报并提示相关人员进行整改。Yo…

SpringBoot工具类—基于定时器完成文件清理功能

直接复制粘贴既可&#xff01;&#xff01; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.io.File; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneOff…

浏览器调起摄像头

浏览器调起摄像头 <template><div class"body">这里什么都没有<video id"videoCamera" class"video"></video><button click"getCompetence" class"btn">打开摄像头</button><butt…

vue管理系统常用命令记录

保留几位小数 //正则let numF (this.countData.hkje * 100) / 1000000sums[index] Number(numF.toString().match(/^\d(?:\.\d{0,4})?/)) 万元; //更正上面的只可以是正数不可以负数&#xff0c;下面的可以是正说或者负数都可以sums[index] Number(numF.toString().matc…

基于jenkins自动化部署PHP环境

实验环境 操作系统 IP地址 主机名 角色 CentOS7.5 192.168.147.141 git git服务器 CentOS7.5 192.168.147.142 Jenkins git客户端 jenkins服务器 CentOS7.5 192.168.147.143 web web服务器 具体环境配置见上一篇&#xff01; 准备git仓库 [rootgit ~]# su -…

Leetcode.100 相同的树

给你两棵二叉树的根节点 p 和 q &#xff0c;编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同&#xff0c;并且节点具有相同的值&#xff0c;则认为它们是相同的。 力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台 代码如下&#xff1a;…

深圳IT行业供需:蓬勃发展的科技中心

深圳作为中国的科技中心之一&#xff0c;IT行业在这座城市蓬勃发展。本文将探讨深圳IT行业的供需状况&#xff0c;包括就业机会、技能需求以及行业前景展望。 近年来&#xff0c;深圳IT行业迅速发展&#xff0c;成为全球科技创新的重要枢纽之一。随着大量的科技企业和初创公司在…

DNS原理

文章目录 一、域名产生背景域名的树形层次化结构 二、定义三、DNS查询模式递归查询迭代查询 四、主机域名解析工作流程五、H3C配置DNS代理 首先可以看下思维导图&#xff0c;以便更好的理解接下来的内容。 一、域名 产生背景 在互联网中&#xff0c;通过IP地址访问目标主机…

固定资产管理措施怎么写

固定资产管理措施是指企业在进行固定资产管理时所采取的各种措施和方法。以下是一些常见的固定资产管理措施&#xff1a;  建立完善的固定资产管理制度。制定明确的资产采购、使用、维护、报废等流程和标准&#xff0c;确保资产管理的规范性和透明度。  采用先进的资产管理…

35 - 个人博客项目-06-首页

1. 自定义html中的过滤器:apps / user / views.py # 自定义过滤器,将二进制内容转成utf-8格式 user_bp.app_template_filter("cdecode") def content_decode(content):content content.decode("utf-8")return content[:200]user_bp.app_template_filter(…

Redis 10 大数据类型

1. which 10 1. redis字符串 2. redis 列表 3. redis哈希表 4. redis集合 5. redis有序集合 6. redis地理空间 7. redis基数统计 8. redis位图 9. redis位域 10. redis流 2. 获取redis常见操作指令 官网英文&#xff1a;https://redis.io/commands 官网中文&#xff1a;https:/…

git difftool对比差异,避免推送不相关内容

问题 在利用git进行版本管理的时候&#xff0c;经常会由于对其他不相关的代码&#xff0c;做了一些小改动&#xff0c;例如删除了一个空行&#xff0c;多了一个缩进等。 为避免将这些不相关的改动也提交到远程&#xff0c;对PR造成不必要的影响&#xff0c;可以利用git diff命…

DolphinDB 携手白鲸开源 WhaleStudio 打造高效敏捷的 DataOps 解决方案

浙江智臾科技有限公司&#xff08;简称&#xff1a;DolphinDB&#xff09;和北京白鲸开源科技有限公司&#xff08;简称&#xff1a;白鲸开源&#xff09;是在大数据技术领域活跃的两支专业团队。 DolphinDB 专注于为用户提供集高性能存储、复杂分析能力和流处理于一体的实时计…

【区块链 | IPFS】浅谈 | IPFS数据存储原理

IPFS在数据存储方面采用的是分散式的文件存储,区别于HTTP协议的位置寻址,IPFS是基于内容寻址,当文件上传到IPFS节点存储时,节点会对文件进行Merkle DAG(默克尔有向无环图)的格式组织分块存储,在存储完毕后,文件将以Merkle DAG的根哈希数来表示该文件,用户可以从IPFS构…

在腾讯云服务器OpenCLoudOS系统中安装svn(有图详解)

1. 安装svn yum -y install subversion 安装成功&#xff1a; 2. 创建数据根目录及仓库 mkdir -p /usr/local/svn/svnrepository 创建test仓库&#xff1a; svnadmin create /usr/local/svn/test test仓库创建成功&#xff1a; 3. 修改配置test仓库 cd /usr/local/svn/te…

ssm+vue校园活动管理平台源码和论文

ssmvue校园活动管理平台源码和论文090 开发工具&#xff1a;idea 数据库mysql5.7 数据库链接工具&#xff1a;navcat,小海豚等 技术&#xff1a;ssm 摘 要 使用旧方法对校园活动信息进行系统化管理已经不再让人们信赖了&#xff0c;把现在的网络信息技术运用在校园活动信…