【问题标题】:How can I set cursor into html text input field?如何将光标设置为 html 文本输入字段?
【发布时间】:2019-11-24 19:52:59
【问题描述】:

对于 Flask 应用程序,我试图将光标设置到表单中的输入文本字段中。表单如下所示:

<form method="get" autocomplete="off">
        <div class="row">
            <div class="four columns">
                <label for="from-currency">Exchange:</label>
                <input type="text" placeholder="currency to exchange from" value="{{ from_curr }}" name="from_currency" id="from-currency" class="input-field"/>
            </div>
            <div class="four columns">
                <label for="to-currency">To:</label>
                <input type="text" placeholder="currency to exchange to" value="{{ to_curr }}" name="to_currency" id="to-currency" class="input-field"/>
            </div>
            <div class="four columns">
                <label for="calculate-button">&nbsp;</label>
                <input type="submit" value="Calculate" id="calculate-button" class="input-field">
            </div>
        </div>
    </form>

我尝试使用 JavaScript (element.focus();),但它没有将光标移动到我的输入字段中。

<script>
    function submit_param(inp) {
        inp.addEventListener("input", function(event) {
            var val = this.value;
            var urlParams = new URLSearchParams(window.location.search);
            urlParams.set(inp.name, val);
            var queryString = urlParams.toString();
            history.pushState({}, "", "?"+queryString);
            location.reload();
            inp.focus();
        });
    }
    submit_param(document.getElementById("from-currency"));
    submit_param(document.getElementById("to-currency"));
</script>

我做错了什么,或者如何将光标移回脚本块末尾的输入字段?

【问题讨论】:

  • 我认为问题在于您在重新加载/刷新页面后调用inp.focus();

标签: javascript html forms


【解决方案1】:

如何将光标设置到 html 文本输入字段中?

<input type="text" autofocus>

自动对焦属性是一个布尔属性。

当存在时,它指定一个元素应该在页面加载时自动获得焦点。

希望这会有所帮助。祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-20
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多