将对象分配给 dom 元素并在函数中检索它

Assigning object to dom element and retrieving it in function

我正在尝试使用 vanilla js 自己构建一个视差插件。基本上我已经全部设置好了,所以它可以工作,但我想做的是添加一些辅助函数,以便稍后用于每个视差部分。

我想要实现的是能够写出类似这样的东西:

document.getElementById('test').parallax.getImage();

在我定义的 js 插件中:

var parallax = {

getImage : function(element, event){
    var img = null;
    var section = element;

    for (var i = 0; i < section.childNodes.length; i++) {
        if (section.childNodes[i].className == "parallax-image") {
          img = section.childNodes[i];
          break;
        }        
    }
    return img;
},

}

稍后在开始时我将对象分配给 dom 元素:

function setupParallax(){
    // this get all sections
    var sections = self.methods.getSections();

    for (var i = sections.length - 1; i >= 0; i--) {
        sections[i].parallax = parallax;
    }
}

所以在视差对象的getImage()函数中,我想检索视差对象分配给的元素。我该怎么做?

通过 parallax namespace 对象扩展 native Element,该对象具有 [=15] 之类的方法=]

document.getElementById('test').parallax.getImage()

您可以使用Fn.prototype.call()将当前部分元素转发到一组(_parallax)使用 Element.parallax

可以访问的方法

const Parallax = (selector) => {

  const
    _el = document.querySelector(selector),
    _sections = _el.querySelectorAll('.parallax-section'),
    _parallax = section => ({
      getImage() {
        return section.querySelector('.parallax-image');
      },
      // more section parallax methods here
    }),
    methods = {};


  methods.getSections = () => _sections;
  methods.someOtherMethod = (arg) => {
    return arg;
  }

  // Init
  [..._sections].forEach(section => section.parallax = _parallax.call(null, section));

  // Expose methods
  return methods;

};


// Init Parallax on some parent
const myPar = Parallax('#container');

// Testing stuff:
console.log( document.getElementById('test').parallax.getImage() );
console.log( myPar.getSections() )
<div id="container">

  <div class="parallax-section">
    <img class="parallax-image" src="//placehold.it/20x20/0bf">
  </div>

  <div id="test" class="parallax-section">
    <img class="parallax-image" src="//placehold.it/20x20/f0b">
  </div>

</div>

上面的 getImage()getImage() 方法的更简单的方法。如果 section.querySelector('.parallax-image') 找不到图像,它将 return null - 就像您的代码一样。