jquery网页代码

从官方网站下载并引入:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Your Page Title</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <!-- Your HTML content and jQuery code go here --> </body> </html>

使用CDN:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Your Page Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> </head> <body> <!-- Your HTML content and jQuery code go here --> </body> </html>

一旦引入了jQuery,你就可以在页面中使用它提供的功能。

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery Example</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <button id="showMessageBtn">Show Message</button> <script> // jQuery code $(document).ready(function(){ // When the button is clicked $("#showMessageBtn").click(function(){ // Display a message alert("Hello, jQuery!"); }); }); </script> </body> </html>

在这个例子中,当按钮被点击时,click事件触发,然后弹出一个包含"Hello, jQuery!"消息的警告框。你可以根据需要扩展和修改这个基本的例子。

1. 选择器:

使用选择器来选择HTML元素,可以根据元素的ID、类、标签等进行选择。

html
<script> $(document).ready(function(){ // 通过ID选择元素 $("#myElement").css("color", "red"); // 通过类选择元素 $(".myClass").hide(); // 通过标签选择元素 $("p").hover(function(){ $(this).css("background-color", "yellow"); }, function(){ $(this).css("background-color", "white"); }); }); </script>

2. 事件处理:

jQuery可以用来处理各种事件,比如点击、鼠标悬停、键盘输入等。

html
<script> $(document).ready(function(){ // 点击事件 $("#myButton").click(function(){ alert("Button clicked!"); }); // 鼠标悬停事件 $("#myElement").hover(function(){ $(this).css("color", "blue"); }, function(){ $(this).css("color", "black"); }); // 键盘事件 $(document).keypress(function(event){ alert("Key pressed: " + String.fromCharCode(event.which)); }); }); </script>

3. 动画效果:

jQuery提供了丰富的动画效果,例如淡入淡出、滑动等。

html
<script> $(document).ready(function(){ // 淡入淡出效果 $("#fadeInBtn").click(function(){ $("#myElement").fadeIn(); }); $("#fadeOutBtn").click(function(){ $("#myElement").fadeOut(); }); // 滑动效果 $("#slideUpBtn").click(function(){ $("#myElement").slideUp(); }); $("#slideDownBtn").click(function(){ $("#myElement").slideDown(); }); }); </script>