只有在没有输入集中的情况下,才将第一个输入集中在负载上
Focus the first input on load only if no input is focused
我正在尝试为我的网站的所有页面设置默认焦点,但在页面重新加载时不更改焦点。
我的意思是:
- 用户打开一个页面
- 焦点在第一次输入时自动设置
- 用户将焦点更改为第三个输入
- 用户刷新页面
- 焦点不得再次更改为第一个输入。(这是我没有达到的要求)
我当前的代码如下:
$(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插件;我用它来简化事情。
相关文章:
- jQuery将输入集中在下一个tr->td时,td包含一个输入字段,但从不关注html选择
- 我如何集中输入'It’s从屏幕上滑进来
- 在输入未填充时将其集中
- 显示给定输入数字的数据集中字母表的所有可能组合
- 如何集中输入,并取消选择其中的文本
- 输入集中,但不可键入
- “map.getBounds()”结果在传单.js集中输入表单后更改
- 将下一个/上一个输入集中在达到最大长度或退格键上
- JQuery 查找集中输入的索引
- 将输入集中在模糊事件不起作用上
- 当输入集中在web应用程序上时显示键盘
- 如何在JavaScript中从字段集中读取输入字段
- AngularJS输入指令在模糊上应用和删除格式&集中
- 只有在没有输入集中的情况下,才将第一个输入集中在负载上
- 如何在不输入关键字的情况下将文本框集中在按键上
- Javascript/jQuery检测输入是否集中
- 防止集中在隐藏溢出区域的集中输入上
- 如何通过javascript或jquery将输入字段集中在Android浏览器上
- 当滚动到输入元素时,我可以集中输入元素吗
- 在jQuery验证中单击提交按钮后没有集中输入