只有在没有输入集中的情况下,才将第一个输入集中在负载上

Focus the first input on load only if no input is focused

本文关键字:集中 输入 第一个 负载 情况下      更新时间:2023-09-26

我正在尝试为我的网站的所有页面设置默认焦点,但在页面重新加载时不更改焦点。

我的意思是:

  • 用户打开一个页面
  • 焦点在第一次输入时自动设置
  • 用户将焦点更改为第三个输入
  • 用户刷新页面
  • 焦点不得再次更改为第一个输入。(这是我没有达到的要求)

我当前的代码如下:

$(document).ready(function() {
    if($(':focus').length === 0) {
        $(':input:not([type="hidden"]):first').focus();
    }
});

条件每次都是真的!

$(document).ready({
window.onload=function(){
if(session.Storage.getItem("text3")){//if key= text3 is set,then change the focus to 3rd text box.
$('#your3rdTextID').focus();
}

$('#your3rdTextID').focus(function(){
    session.Storaage.setItem("text3","selected")//here you set the key as text3 and value as selected for later use.
});

});

您可以提供自己的自定义条件。这只是一个小例子。希望它能帮助你。祝你的项目好运。

链接-->HTML5本地存储与会话存储

链接-->http://www.w3schools.com/html/html5_webstorage.asp

这将起作用(在最新的Chrome、IE7和IE10中测试)。将cookie设置为焦点,记住最后一个焦点元素,如果没有,则默认为第一个。它依赖于jquery.cookie.js(在这个SO答案中解释了用法)。以下是一个最小工作示例的完整HTML+JS源代码。考虑更改cookie名称和输入选择器(当前为'input'):

<!doctype html>
<html>
<head>
    <title>focus test</title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.cookie.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var $input = $('input'), // get all the inputs
                cookieName = 'lastInputFocusIndex', // for consistency
                lastIndex = $.cookie(cookieName) || 0; // get the last known index, otherwise default to zero
            $input.on('focus',function(){ // when any of the selected inputs are focused
                if ( $(this).attr('type') !== 'submit' ) {
                    $.cookie(cookieName,$input.index(this)); // get their index in the $input list and store it
                }
            });
            $input.eq(lastIndex).focus(); // when the page loads, auto focus on the last known index (or the default of 0)
        });
    </script>
</head>
<body>
<form method="get" action="">
    <p><input type="text" name="first" /></p>
    <p><input type="text" name="second" /></p>
    <p><input type="text" name="third" /></p>
    <p><input type="submit" value="Go" /></p>
</form>
</body>
</html>

或者,您可以编写自己的原始cookie,而不是使用cookie助手jQuery插件;我用它来简化事情。