代码之家  ›  专栏  ›  技术社区  ›  damiano celent

向原型方法添加回调函数并设置此上下文

  •  0
  • damiano celent  · 技术社区  · 9 年前

    我想在单击时显示对象的一些关键值。每个按钮都有一个点击监听器,为员工的各种实例调用原型方法。

    这很管用。

    但我希望输出方法在单击按钮时执行以下操作: -不透明度:0,然后将#demo的高度滑动到1px(非常小),然后当新的innerHTML值位于#demo中时,将高度动画化为30px,不透明度动画化为0。 我尝试了多种方式传递回调函数,但总是出现类型错误。 下一个问题是如何在使用addEventListener时正确设置此上下文,以及是否可以为每个eventListener分配不同的函数?

    function employee(name, jobtitle, born) {
    this.name=name;
    this.jobtitle=jobtitle;
    this.born=born;
    this.callback = function(){};
     }
    
    employee.prototype.output = function(){
    var pee = document.querySelector("p");
    pee.style.opacity = 0;
    
    pee.style.height = "30px";
    pee.style.opacity = 1;
    return this.name + "is a " + this.jobtitle + " born in the year" + this.born};
    

    链接到代码笔:

    http://codepen.io/damianocel/pen/MeaeGX

    请只使用Javascript,我可以在Jquery中获得它,但对于如何在vanilla JS中实现这一点,仍有一些学习要做。

    1 回复  |  直到 9 年前
        1
  •  1
  •   trincot Jakube    9 年前

    您已经使用CSS transition ,所以对于第一个问题,在放置文本并将高度设置回 30px ,否则立即中断动画。为此,你可以听听 transitionend 事件

    我还建议不要设置 style 属性,但要改用类。您还需要剪切文本 not overflow 设置高度动画时。

    对于第二个问题:您可以使用 bind 生成已具有的函数引用 this 可能还有一些固定的参数。

    以下是对这些点进行了一些修改后的代码:

    function employee(name, jobtitle, born) {
        this.name=name;
        this.jobtitle=jobtitle;
        this.born=born;
        this.callback = function(){};
    }
    
    employee.prototype.output = function(target){
        var whenHidden = function () {
            target.textContent = this.name + " is a " + this.jobtitle + 
                                 " born in the year " + this.born;
            target.removeEventListener('transitionend', whenHidden);
            target.classList.remove('hide');
        }.bind(this);
        target.addEventListener('transitionend', whenHidden);
        target.classList.add('hide');
    };
    
    var fred = new employee("Fred Flintstone", "Caveman", 1970);
    var mike = new employee("Mike Francois", "Wrestler", 1965);
    var demo = document.getElementById("demo");
    var output = employee.prototype.output;
    
    document.getElementById("a").addEventListener('click', output.bind(fred, demo));
    document.getElementById("b").addEventListener('click', output.bind(mike, demo));
    p { 
      border:2px black solid;
      transition:.5s;
      height:30px;
      text-overflow: clip;
      overflow: hidden;
      opacity: 1;
    }
    p.hide {
      height: 1px;
      opacity: 0.1;
    }
    <button id="a">Fred</button>
    <button id="b">Mike</button>
    <button id="c">Tom</button>
    <p id="demo"></p>