js 焦点事件

焦点:使浏览器能够区分用户输入的对象,当一个元素有焦点的时候,那么他就可以接收用户的输入。

我们可以通过一些方式给元素设置焦点

1 点击

2 tab

3 js

不是所有元素都能够接收焦点,能够相应用户操作的元素才有焦点

onfocus:当元素获取到焦点的时候触发

onblur:当元素失去焦点的时候触发

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{CHARSET}">
        <title></title>
        <script>
            window.onload = function(){
                var oText = document.getElementById('text1');
                oText.onfocus = function(){
                    if(this.value == '请输入内容'){
                        this.value = '';
                    }
                }
                oText.onblur = function(){
                    if(this.value == ''){
                        this.value = '请输入内容';
                    }
                }
            }
        </script>
    </head>
    <body>
        <input type="text" id="text1" value="请输入内容" />
    </body>
</html>

obj.focus() 给指定的元素设置焦点

obj.blur() 取消指定的元素焦点

obj.select() 选择制定元素里面的文本内容(注意:选中的是可交互性的文本内容,如input)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="{CHARSET}">
        <title></title>
        <script>
            window.onload = function(){
                var oText = document.getElementById('text1');
                oText.onfocus = function(){
                    if(this.value == '请输入内容'){
                        this.value = '';
                    }
                }
                oText.onblur = function(){
                    if(this.value == ''){
                        this.value = '请输入内容';
                    }
                }
                oText.focus();
                var oBtn = document.getElementById('btn');
                oBtn.onclick = function(){
                    oText.select();
                }

            }
        </script>
    </head>
    <body>
        <input type="text" id="text1" value="请输入内容" />
       <input type="button" id="btn" value="全选" />
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_35187942/article/details/85932866
今日推荐