Vanilla JS-swup.js页面转换后重新初始化函数

时间:2019-06-09 10:41:36

标签: javascript

我对JS还是很陌生,并且正在使用swup.js(一个很棒的库btw)在站点的页面之间进行转换。过渡效果很好,但是过渡后,我需要重新初始化一些我拥有的JS函数。

根据swup.js文档,我只是将它们包装在swup事件中。在以下情况下我该怎么做?我想我特别需要将两个函数重新添加到两个buttonLeft / buttonRight常量中。

此处的示例:https://swup.js.org/getting-started/reloading-javascript


//JS in script tag at bottom of body
    const swup = new Swup();
        init();
        swup.on('contentReplaced', init);


// Function called in my main.js file
function init() {
    if (document.querySelector('')) { // What do I include here?
        // What do I include here?
    }


// Functions I'd like reinitialized (also in main.js)
const buttonRight = document.getElementById('slide-right');
const buttonLeft = document.getElementById('slide-left');
buttonLeft.onclick = scrollLeft; 
buttonRight.onclick = scrollRight;

function scrollLeft() {
  document.getElementById('hoz-scroller').scrollTo({ left: 0, behavior: 'smooth' }); 
  buttonLeft.classList.add('disabled'); 
  if (buttonRight.classList.contains('disabled')) { 
    buttonRight.classList.remove('disabled'); 
  }
};

function scrollRight() {
  document.getElementById('hoz-scroller').scrollTo({ left: elementWidth, behavior: 'smooth' }); 
  buttonRight.classList.add('disabled'); 
  if (buttonLeft.classList.contains('disabled')) { 
  buttonLeft.classList.remove('disabled'); 
  }
};

1 个答案:

答案 0 :(得分:0)

回答了我自己的问题。感谢这些人:https://openclassrooms.com/en/courses/3523231-learn-to-code-with-javascript/4379006-use-constructor-functions。为所有其他菜鸟提供以下答案:

基本上,您需要将单独的函数包装到一个新函数中,并在swup init函数中调用它:

function init() {
    if (document.querySelector('#hoz-scroller')) { //This checks if this element is on the the page (in the html)
        new scrollers(); // If it is then it creates a new instance of the 'scrollers' function
    }
}
var scrollStart = new scrollers(); // This initialises the below function the first time (first page load not controlled by swup)

function scrollers() { // This it the wrapper funtion

  const element = document.getElementById("hoz-scroller"); 
  const elementRect = element.getBoundingClientRect(); 
  const elementWidth = elementRect.width;  
  const elementMiddle = (elementWidth / 2 - 50); 
  element.scrollTo(elementMiddle, 0); 

  const buttonRight = document.getElementById('slide-right'); 
  const buttonLeft = document.getElementById('slide-left');
  buttonLeft.onclick = scrollLeft; 
  buttonRight.onclick = scrollRight;

  function scrollLeft() {
    document.getElementById('hoz-scroller').scrollTo({ left: 0, behavior: 'smooth' });  
    buttonLeft.classList.add('disabled'); 
    if (buttonRight.classList.contains('disabled')) { 
      buttonRight.classList.remove('disabled'); 
    }
  };
  function scrollRight() {
    document.getElementById('hoz-scroller').scrollTo({ left: elementWidth, behavior: 'smooth' }); 
    buttonRight.classList.add('disabled'); 
    if (buttonLeft.classList.contains('disabled')) { 
    buttonLeft.classList.remove('disabled');
    }
  };
};