焦点不适用于由javascript onclick事件触发的textarea

时间:2015-06-28 09:25:52

标签: javascript jquery

我有一个简单的过渡事物,其中一条消息显示“点击此处键入”这样的内容,这是一个div,当单击时,隐藏此div并显示带有闪烁光标的textarea。当页面最初加载时,我通过onload集中注意力但是我想要在需要时触发焦点。

所以我有这样的事情:

界面

<div id="message" onclick="showPad();"><span class="message">Click to write</span></div>
<form name="entry">
<textarea id="writingpad" name="writingpad" placeholder="write here"></textarea>
</form>

javascript

<script>
function showPad() {
document.getElementById('message').style.display = "none";
document.getElementById('writingpad').style.display = "inline-block";

// this is what I've tried for focus

document.entry.writingpad.focus(); // didn't work
$('#writingpad').live('focus', function() {
// document.entry.input.focus(); possibly redundant
}
$('#writingpad').focus(); // doesn't work
}
</script>

工作脚本

function showPad() {
$('#writingpad').focus();
}

2 个答案:

答案 0 :(得分:2)

脚本中的焦点有效,问题在于加载。

您可以确保将脚本放在onLoad<head>中,而不是使用<body>和直播活动委派。

也不需要jQuery - 纯JS:

var message  = document.getElementById('message');
var textarea = document.getElementById("writingpad");

function showPad() {
    message.style.display = "none";
    textarea.style.display = "inline-block";
    textarea.focus();
}

Demo

答案 1 :(得分:1)

这应该适合你。

&#13;
&#13;
$(document).ready(function() {
  $('#message').click(function() {
    $(this).hide();
    $('#writingpad').css('display', 'inline-block').focus();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"><span class="message">Click to write</span></div>
<form name="entry">
  <textarea id="writingpad" name="writingpad" placeholder="write here"></textarea>
</form>
&#13;
&#13;
&#13;

修改

您的版本无法正常工作的原因是因为您具有忘记关闭它的功能。

$('#writingpad').live('focus', function() {
      // document.entry.input.focus(); possibly redundant
}

应该是:

$('#writingpad').live('focus', function() {
      // document.entry.input.focus(); possibly redundant
});

检查

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  function showPad() {
    document.getElementById('message').style.display = "none";
    document.getElementById('writingpad').style.display = "inline-block";

    // this is what I've tried for focus

    document.entry.writingpad.focus(); // didn't work
    $('#writingpad').live('focus', function() {
      // document.entry.input.focus(); possibly redundant
    });
    $('#writingpad').focus(); // doesn't work
}
</script>

<div id="message" onclick="showPad();">
  <span class="message">Click to write</span>
</div>
<form name="entry">
  <textarea id="writingpad" name="writingpad" placeholder="write here"></textarea>
</form>
&#13;
&#13;
&#13;