• 全局引入的js如何只让部分页面有效


    目录

    问题:

    解决方案:


    问题:

    我不想让所有页面都有这个js效果,只想让部分页面有,应该怎么办?(不改变全局引入的情况下)

    解决方案:

    1、使用条件语句判断当前页面是否需要应用该效果: 在你的js文件中添加一个判断条件,只在符合条件的页面中执行相应的代码。(以鼠标监听为例):将"需要应用该效果的页面URL"替换为实际需要应用该效果的页面的URL

    1. const headerDom = document.querySelector("#header");
    2. var scrollFunc = function (e) {
    3. var e = e || window.event;
    4. if (e.wheelDelta) {
    5. if (e.wheelDelta > 0) { //当鼠标滚轮向上滚动时
    6. headerDom.classList.remove('hide');
    7. }
    8. if (e.wheelDelta < 0) { //当鼠标滚轮向下滚动时
    9. headerDom.classList.add('hide');
    10. }
    11. } else if (e.detail) {
    12. if (e.detail < 0) { //当鼠标滚轮向上滚动时
    13. headerDom.classList.remove('hide');
    14. }
    15. if (e.detail > 0) { //当鼠标滚轮向下滚动时
    16. headerDom.classList.add('hide');
    17. }
    18. }
    19. }
    20. // 判断当前页面是否需要应用该效果
    21. if (window.location.href.includes("需要应用该效果的页面URL")) {
    22. // 给页面绑定鼠标滚轮事件
    23. window.addEventListener("DOMMouseScroll", scrollFunc);
    24. window.addEventListener("wheel", scrollFunc);
    25. window.addEventListener("mousewheel", scrollFunc);
    26. }

    window.location.href.includes("需要应用该效果的页面URL")中可以写多个页面URL,以实现在多个页面上应用该效果。

    格式可以使用逻辑运算符 来组合多个URL。具体格式如下:||

    1. if (window.location.href.includes("页面URL1") || window.location.href.includes("页面URL2") || ...) {
    2. // 给页面绑定鼠标滚轮事件
    3. window.addEventListener("DOMMouseScroll", scrollFunc);
    4. window.addEventListener("wheel", scrollFunc);
    5. window.addEventListener("mousewheel", scrollFunc);
    6. }

    2、动态添加或移除脚本标签: 在需要应用该效果的页面上,通过JavaScript动态创建一个新的script标签,并将原有的js文件链接添加到该标签中

    1. // 创建script标签元素
    2. var script = document.createElement("script");
    3. // 设置script标签的src属性为原有的js文件链接
    4. script.src = "原有的js文件链接";
    5. // 将script标签添加到页面的头部或尾部
    6. document.head.appendChild(script);

    将"原有的js文件链接"替换为实际的js文件链接。

  • 相关阅读:
    mysql数据模型
    Pytorch入门实例的分解写法
    计算机网络 第二节
    前端vue面试题
    Python机器学习实战-特征重要性分析方法(2):内置特征重要性(附源码和实现效果)
    关于网络协议的若干问题(五)
    ubuntu 22.04 安装python-pcl
    Spring 常用注解及作用
    计算机毕业设计Java中华美食文化网站(源码+系统+mysql数据库+Lw文档)
    SpringBoot
  • 原文地址:https://blog.csdn.net/qq_62799214/article/details/132956646