我想创建一个链接,将用户带到文本区域并允许他们立即开始在其中输入内容。这是我的文本区域:
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>
目前,我只是通过以下方式链接到它:
<a href="#commentnow">Post a comment</a>
但这只会将他们带到文本区域所在的区域,而不是在文本区域内部,以便他们可以开始输入。为此,他们显然需要点击它。我创建了一个 fiddle使用我当前的设置。
我认为对此有多种解决方案。然而,我会要求一个以兼容性为中心的解决方案(适用于所有浏览器,尤其是手机浏览器)。
最佳答案
将 .focus()
方法与 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>
使用 return false
或 preventDefault()
让它在任何地方都有效。 Android 上的 Chrome/stock 浏览器不需要这个。 Firefox 移动版可以。
关于javascript - 链接到文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14072774/