首页 > 解决方案 > 如何在不破坏任何功能的情况下使用 barba.js 运行其他 JS 文件

问题描述

我正在使用 barba.js 进行页面转换,但是当我使用它时,我的其他 js 文件会中断。

这是我的网站

我创建了一个在所有其他 JS 文件上实现的runScript函数,但它仍然无法正常工作。

我做错了什么,我该如何解决?

这是其中一个 JS 文件的 runscript 函数:

const runScript = () => {
    const footer = document.querySelector('footer');

    barba.hooks.leave((data) => {
        footer.style.opacity = 0;
    });

    barba.hooks.afterEnter((data) => {
        footer.style.opacity = 1;
    });

}


runScript()

barba.init({
    transitions: [
        {
            name: "switch",
            leave({ current, next, trigger }) {

            },
            enter({ current, next, trigger }) {
                runScript()
                runScriptc()

                return new Promise(resolve => {
                    setTimeout(resolve, 2000)
                })
            }
        }
    ],
    views: [],
    debug: true
})

标签: javascriptbarbajs

解决方案


我假设您使用的是 BarbaJs v2。在这种情况下,您不需要在每个 js 文件中声明该页脚行为。您没有分配transition from-to属性,而且您缺少一些括号和分号。您只需要一个 js 文件(或 typescript 转译文件)即可使其正常工作。尝试使用这个:

const runScript = () => {
  const footer = document.querySelector('footer');

  barba.hooks.beforeLeave((data) => {
      footer.style.opacity = 0;
  });

  barba.hooks.afterEnter((data) => {
      footer.style.opacity = 1;
  });

}


runScript();

barba.init({
    transitions: [{

            name: "switch",

            from: { namespace : [ 'homepage' ] }, //set the "from" namespaces.

            to: { namespace : [ 'about', 'contact' ] }, //set the "to" namespaces.

            beforeLeave({ current, next, trigger }) { //before leaving the page.
                 //Begin your transition and return "resolve" when is completed.
                 return new Promise(resolve => {
                    setTimeout(resolve, 2000);
                 })
            },
            afterEnter({ current, next, trigger }) {
                 //remove the transition (is not necessary to return a promise, at this point barba doesn't check for promises).

            }
        }],
    views: [],
    debug: true
});

Barba.hooksproperties 允许您在每次节时声明一个行为enters, or leave

请记住,始终在您将使用的 HTML 页面上设置barba-barba="wrapper"和标记。例如:data-barba="container"data-barba-namespace="homepage" (or about or contact)

<div class="main-wrapper" data-barba="wrapper"> 

    <!-- Content that will not change -->

    <section data-barba="container" data-barba-namespace="homepage"> 

        <!-- Content that will change --> 

    </section>
 </div>

您可以查看BarbaJs v2 文档以获取有关转换的更多信息。


推荐阅读