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

时间:2018-07-01 11:52:31

标签: javascript object domdocument

我正在尝试使用香草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()函数中,我想检索分配了视差对象的元素。我该怎么办?

1 个答案:

答案 0 :(得分:1)

通过Element 命名空间对象扩展 native parallax对象,该对象具有类似.getImage()

的方法
document.getElementById('test').parallax.getImage()

您可以使用Fn.prototype.call()将当前 section 元素转发到一组(_parallax)方法,可以使用{ {1}}

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')-就像您的代码一样。