目录
问题:
我不想让所有页面都有这个js效果,只想让部分页面有,应该怎么办?(不改变全局引入的情况下)
解决方案:
1、使用条件语句判断当前页面是否需要应用该效果: 在你的js文件中添加一个判断条件,只在符合条件的页面中执行相应的代码。(以鼠标监听为例):将"需要应用该效果的页面URL"替换为实际需要应用该效果的页面的URL
const headerDom = document.querySelector("#header"); var scrollFunc = function (e) { var e = e || window.event; if (e.wheelDelta) { if (e.wheelDelta > 0) { //当鼠标滚轮向上滚动时 headerDom.classList.remove('hide'); } if (e.wheelDelta < 0) { //当鼠标滚轮向下滚动时 headerDom.classList.add('hide'); } } else if (e.detail) { if (e.detail < 0) { //当鼠标滚轮向上滚动时 headerDom.classList.remove('hide'); } if (e.detail > 0) { //当鼠标滚轮向下滚动时 headerDom.classList.add('hide'); } } } // 判断当前页面是否需要应用该效果 if (window.location.href.includes("需要应用该效果的页面URL")) { // 给页面绑定鼠标滚轮事件 window.addEventListener("DOMMouseScroll", scrollFunc); window.addEventListener("wheel", scrollFunc); window.addEventListener("mousewheel", scrollFunc); }
window.location.href.includes("需要应用该效果的页面URL")中可以写多个页面URL,以实现在多个页面上应用该效果。格式可以使用逻辑运算符 来组合多个URL。具体格式如下:
||
if (window.location.href.includes("页面URL1") || window.location.href.includes("页面URL2") || ...) { // 给页面绑定鼠标滚轮事件 window.addEventListener("DOMMouseScroll", scrollFunc); window.addEventListener("wheel", scrollFunc); window.addEventListener("mousewheel", scrollFunc); }2、动态添加或移除脚本标签: 在需要应用该效果的页面上,通过JavaScript动态创建一个新的script标签,并将原有的js文件链接添加到该标签中
// 创建script标签元素 var script = document.createElement("script"); // 设置script标签的src属性为原有的js文件链接 script.src = "原有的js文件链接"; // 将script标签添加到页面的头部或尾部 document.head.appendChild(script);将"原有的js文件链接"替换为实际的js文件链接。