如何使用jQuery获得焦点元素
为了聚焦元素,jQuery有一个内置的选择器,它被用来检测当前聚焦的元素。当元素被鼠标点击或标签导航按钮聚焦时,这个选择器会返回所选元素。你可以在JQuery中添加元素,以便轻松地关注该元素。这里我们将使用JQuery内置的选择器$(“:focus”)
语法:
$(":focus")
例子1:这个例子展示了如何使用jQuery来聚焦一个元素。
<!DOCTYPE html>
<html>
<head>
<title>
How to get focused element
using jQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("input").focus();
$(":focus").css("background-color", "yellow");
});
</script>
<style>
.geeks {
width: 350px;
height: 100px;
border: 2px solid green;
padding-bottom: 15px;
margin: 10px;
}
h1 {
color:green;
}
</style>
</head>
<body>
<center>
<div class="geeks">
<h1>GeeksforGeeks</h1>
<input type="text" placeholder="Focused Input" />
</div>
</center>
</body>
</html>
输出:
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>
How to get focused element
using jQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
(document).ready(function(){
("input").focus();
(":focus").css("background-color", "red");
("button").focus();
$(":focus").css("background-color", "green");
});
</script>
<style>
.geeks {
width: 350px;
height: 100px;
border: 2px solid green;
padding-bottom: 15px;
margin: 10px;
}
h1 {
color:green;
}
</style>
</head>
<body>
<center>
<div class="geeks">
<h1>GeeksforGeeks</h1>
<input type="text" placeholder="Focused Input" />
<button type="button" >
<a href="https://ide.geeksforgeeks.org/tryit.php">
Click me visit ide
</a>
</button>
</div>
</center>
</body>
</html>
输出: