1

我想创建一个链接,将用户带到 textarea 并允许他们立即开始输入。这是我的文本区域:

<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>

目前,我只是通过以下方式链接到它:

<a href="#commentnow">Post a comment</a>

但这只会将他们带到 textarea 所在的区域,而不是在其中,以便他们可以开始输入。为了做到这一点,他们显然需要点击它。我用我当前的设置创建了一个小提琴。

我想对此有多种解决方案。但是,我会要求一个以兼容性为中心的解决方案(适用于所有浏览器,尤其是手机浏览器)。

4

3 回答 3

7

Use the .focus() method along with window.location.hash.

<a href="#comment" onclick="window.location.hash = 'comment'; document.getElementById('comment').focus(); return false;">click</a>
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>

Use return false or preventDefault() for this to work everywhere. Chrome/stock browser on android doesn't require this. Firefox mobile does.

Here's the fiddle for you to test with. Here's another example fiddle where the submit is visible while typing.

于 2012-12-28T16:46:53.583 回答
1

当可以使用普通的 HTML 元素时,您不需要为此使用 JavaScript;考虑到这一点,只需使用一个label元素,而不是一个a,因为您的要求正是由label元素满足:

<label for="commentnow">Post a comment</label>
<textarea id="commentnow" name="comment" cols="45" rows="8" aria-required="true"></textarea>​

JS 小提琴演示

for属性label必须等于id您要关注并与之关联的元素的label

回应 OP 的评论(在评论中,如下):

两个问题:兼容性如何?如何使它成为可点击文本的按钮(悬停时光标会发生变化)......?

为了解决兼容性问题,该label元素从 HTML 4.01 开始就已经存在,而且我还没有遇到过不能使用它的浏览器(包括 IE 7,但我不记得在 IE 6 中使用过它)。

要让它看起来像一个按钮,只需使用 CSS(就像您将a元素样式设置为像一个按钮一样,例如:

label {
    color: #666;
    display: inline-block;
    padding: 0.3em 0.5em;
    border: 1px solid #aaa;
    background-color: #eee;
    margin: 0.5em;
}

label:hover,
label:active,
label:focus {
    color: #f90;
    box-shadow: 0 0 0.3em #f90;
}

JS Fiddle 演示,这不是一个特别漂亮的示例,但确实表明样式可能性都存在,并且在这方面与任何其他元素没有什么不同。

于 2012-12-28T16:50:48.860 回答
0

使用 jQuery 简单尝试一下:

<a class="link" href="#">Post a comment</a>
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea

$(".link").click(function(){
    $("#comment").focus();
    return false;
});
于 2012-12-28T17:08:57.820 回答