Định nghĩa và sử dụng .focus() trong jQUery

.focus(): Xử lý một sự kiện focus, hoặc kích hoạt sự kiện focus cho thành phần.

Cấu trúc .focus() trong jQUery

Đã được thêm vào từ phiên bản 1.0

.focus()

$('input').focus();
.focus(function(){...});

$('input').focus(function(){
    $('span').text('Thành phần được focus');
});

.focus()

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
    $('p').click(function(){
        $('input').focus();
    });
});
</script>
</head>

<body>
<p>Click để focus</p>
<input type="text" value="" />
</body>
</html>

Hiển thị trình duyệt:

Khi click vào dòng text Click để focus thì lập tức focus của input đã được kích hoạt.

.focus(function(){...});

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Tiêu đề</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
span { display: none; }
</style>
<script>
$(function(){
    $('input').focus(function(){
        $(this).next('span').css('display','inline').fadeOut(1200);
    });
});
</script>
</head>

<body>
<p><input type="text" value="" /> <span>Focus</span></p>
<p><input type="text" value="" /> <span>Focus</span></p>
</body>
</html>

Hiển thị trình duyệt:

Click vào trường input để thấy kết quả.

Viết câu trả lời

Drop Images

0 Bình luận