• 全局引入的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文件链接。

  • 相关阅读:
    Webrtc丢包率的计算
    图片格式 jpg png gif webp svg
    Pulsar Manager配置自定义认证插件访问
    kubernetes集群之调度系统
    LVS+Keepalived 高可用集群负载均衡
    合作动态 | 方正璞华与日立签订战略合作协议,加快推进数字化管理变革!
    外贸独立站为什么需要做邮件营销
    【概率论笔记】正态分布专题
    阿里云Intel Xeon Platinum可扩展处理器性能说明
    数据权限技术调研
  • 原文地址:https://blog.csdn.net/qq_62799214/article/details/132956646