2

我正在尝试创建一个自定义指令,其中包含一个文本框,当用户单击按钮时,该文本框会显示、展开和聚焦。当用户点击展开的文本框时,它应该最小化,消失然后显示原始按钮。这是我到目前为止所拥有的:http: //jsfiddle.net/Z6RzD/152/

这是我遇到问题的部分:

  if (htmlTxtBox.addEventListener !== undefined) { 
  console.log("first");

  htmlTxtBox.addEventListener('focus', setFocus(), false);
  //this function is automatically called even when textBox is in focus              
  //htmlTxtBox.addEventListener('blur', setNoFocus(), false);
  console.log("ifHasFocus: " + scope.showInput);
} else if (htmlTxtBox.attachEvent != undefined) {
  console.log("second");
  htmlTxtBox.attachEvent('onfocus', setFocus());
  htmlTxtBox.attachEvent('onblur', setNoFocus());
} else {
  console.log("third");
  htmlTxtBox.onmouseover = setFocus();
  htmlTxtBox.onmouseout = setNoFocus();
}

以及与事件侦听器一起运行的相应函数:

function setFocus()  {
        scope.$apply('showInput = true');
        console.log("setFocus: " + scope.showInput);    
    }
function setNoFocus(){
  scope.$apply('showInput = false');
  console.log("setNoFocus: " + scope.showInput);
}

我的问题是 setFocus 和 setNoFocus 函数无论如何都会运行。我如何才能将这些函数构建到仅在文本框聚焦或模糊时才运行的位置?我很感激任何帮助。谢谢!

4

2 回答 2

5

试试这个:

myApp.directive('replybox', function($timeout) {
    var linkFn = function(scope, element, attrs) {       
        scope.showInput = false;

        var button = element.find('button');        
        var input = element.find('input');

        button.bind("click", function() {
            scope.showInput = true;
            scope.$apply();

            input[0].focus();
            input.css({"width":"300px","transition":"1s"});            
        });

        input.bind('blur', function() {
            scope.showInput = false;            
            $timeout(function() { scope.$apply(); }, 1000);

            input.css({'width':'0px', 'transition':'1s'});
        });
    };    
...

jsFiddle在这里

于 2013-08-26T21:14:17.133 回答
0

老问题,但要解决实际问题:

我相信htmlTxtBox.addEventListener('focus', setFocus(), false);应该只是setFocus将引用传递给函数,而不是在 addEventListener 调用中调用它。

于 2018-10-11T17:01:18.737 回答