onFocus表现出奇怪的行为

时间:2014-06-24 19:12:52

标签: javascript javascript-events onfocus

我对onFocus的行为感到有些困惑。我有一个带有几个textarea的表单,我希望它们的表现与输入[:text]字段大致相同,也就是说,当用户选中或单击该字段时,字段中的所有文本都被选中。 mozilla网站上的文档说,只要用户通过鼠标点击或Tab键输入字段,就会触发onFocus,因此它似乎是一个理想的事件。但是它没有像我期望的那样表现。

我假设以下代码可行:

e.addEventListener('focus',function(){e.select()})

但事实并非如此。但是,使用onClick工作正常:

e.addEventListener('click',function(){e.select()})

除了当用户通过鼠标点击而不是通过制表符输入字段时,它仅选择字段中的文本。经过一段时间的游戏,我发现这有效:

e.addEventListener('focus',function(){setTimeout(function(){e.select()},0)})

我已经在Safari 7和Chrome 35上对此进行了测试.Firefox 29有点可行,但我还没弄清楚它在做什么。

有人可以解释我所缺少的东西吗?

我已经包含了一个示例页面,说明了我一直在讨论的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/html5/strict.dtd">
<html>
<head>
<script type="text/javascript">
    function init() {
        var e = document.forms[0].elements
        e[0].value = "fld1: "
        e[0].addEventListener('focus',function(event){
                e[0].value += "onfocus, "
                e[0].select()
            })
        e[1].value = "fld2: "
        e[1].addEventListener('focus',function(event){
                e[1].value += "onfocus, "
                setTimeout(function(){e[1].select()},0)
            })
        e[2].value = "fld3: "
        e[2].addEventListener('click',function(event){
                e[2].value += "onclick, "
                e[2].select()
            })
    }
</script>
</head>

<body onload="init()">
<form>
    <textarea rows=4 cols=80></textarea>
    <br/><br/>
    <textarea rows=4 cols=80></textarea>
    <br/><br/>
    <textarea rows=4 cols=80></textarea>
</form>
</body>

1 个答案:

答案 0 :(得分:0)

就Vanilla JS而言,问题很可能在于将EventListener附加到适当的元素上。这可以通过获取所有元素(按类名或类似名称),以类似数组的格式循环遍历并以这种方式附加EventListener函数来完成。

HTML:

<div class="row d-flex justify-content-center">
    <div class="col-md-6">
        <input type="text" class="form-control auto-selector" value="Some input field text value" />
    </div>
</div>
<br />
<div class="row d-flex justify-content-center">
    <div class="col-md-6">
        <textarea class="form-control auto-selector">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet felis vel lacus auctor, nec sollicitudin leo blandit. Praesent arcu tellus, fringilla id efficitur ut, interdum vitae risus. Aliquam erat volutpat. Aenean eleifend dui vel blandit facilisis. Curabitur vel libero ut erat ultricies pretium. Proin congue, orci sed dignissim consequat, nunc massa scelerisque ante, in efficitur est sem ac nulla. Aliquam at est sed ligula lobortis feugiat ut et nisl.</textarea>
    </div>
</div>

香草JS:

var elements = document.getElementsByClassName('auto-selector');

Array.from(elements).forEach(function(element) {
    element.addEventListener("focus", function(e) {
        this.focus();
        this.select();
    });
});

代码段示例:

var elements = document.getElementsByClassName('auto-selector');

Array.from(elements).forEach(function(element) {
    element.addEventListener("focus", function(e) {
        this.focus();
        this.select();
    });
});
textarea.auto-selector {
  width: 100%;
  height: 200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row d-flex justify-content-center">
    <div class="col-md-6">
        <input type="text" class="form-control auto-selector" value="Some input field text value" />
    </div>
</div>
<br />
<div class="row d-flex justify-content-center">
    <div class="col-md-6">
        <textarea class="form-control auto-selector">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet felis vel lacus auctor, nec sollicitudin leo blandit. Praesent arcu tellus, fringilla id efficitur ut, interdum vitae risus. Aliquam erat volutpat. Aenean eleifend dui vel blandit facilisis. Curabitur vel libero ut erat ultricies pretium. Proin congue, orci sed dignissim consequat, nunc massa scelerisque ante, in efficitur est sem ac nulla. Aliquam at est sed ligula lobortis feugiat ut et nisl.</textarea>
    </div>
</div>

Codepen示例here

如果您能够/允许使用jQuery,则解决方案将变得更加容易。

jQuery:

$('.auto-selector').on("focus", function() {
    $(this).select();
});

代码段示例:

$('.auto-selector').on("focus", function() {
    $(this).select();
});
textarea.auto-selector {
  width: 100%;
  height: 200px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row d-flex justify-content-center">
    <div class="col-md-6">
        <input type="text" class="form-control auto-selector" value="Some input field text value" />
    </div>
</div>
<br />
<div class="row d-flex justify-content-center">
    <div class="col-md-6">
        <textarea class="form-control auto-selector">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet felis vel lacus auctor, nec sollicitudin leo blandit. Praesent arcu tellus, fringilla id efficitur ut, interdum vitae risus. Aliquam erat volutpat. Aenean eleifend dui vel blandit facilisis. Curabitur vel libero ut erat ultricies pretium. Proin congue, orci sed dignissim consequat, nunc massa scelerisque ante, in efficitur est sem ac nulla. Aliquam at est sed ligula lobortis feugiat ut et nisl.</textarea>
    </div>
</div>

Codepen示例here