用js或者jquery怎样实现点击一个按钮将光标锁定的指定文本框,点击页面其他地方光标依然在文本框,求帮忙。

用js或者jquery怎样实现点击一个按钮将光标锁定的指定文本框,点击页面其他地方光标依然在文本框,求帮忙。,第1张

<input id=txt1 type=text value="1234"/>

<input id=txt2 type=text value="5678"/>

<button id=btn>click</button>

<script>

window.onload=function(){

   btn.onclick=function(){

      document.onclick=function(){

         txt1.focus()  //点击页面其他地方光标依然在txt1

      }

      txt1.focus()

   }

}

</script>

js

document.getElementById(id).focus()

例如

<input id="shan" type="text" onchange ="return gaib(this.id)"/>

function gaib(id) {

var oo=document.getElementById(id)

if (oo.value == 3) {

alert('输入错误')

oo.focus()

}

}

jquery

$("#"+id).focus()

例如

<input id="shan" type="text" onchange ="return gaib(this.id)"/>

function gaib(id) {

var oo=$("#"+id)

if (oo.val() == 3) {

alert('输入错误')

oo.focus()

}

}

思路:首先获取这个新创建的input对象,然后使用focus()方法设置焦点

示例如下——点击按钮创建一个input,并使其获得焦点:

1、HTML结构

<ul>

    <li><input type="text"></li>

    <li></li>

</ul>

<input type="button" value="添加">

2、jquery代码

$(function(){

    $("input:button").click(function() {

        pwd = $("<input type='password'>")    // 创建的input对象

        $("ul li:last").append(pwd)                        // 将创建的input添加到相应的位置

        $("ul li:last input").focus()                        // 获取新添加的input,使用focus()设置焦点

    })

})

3、效果演示


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/tougao/11232150.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存