当前位置: 首页 > news >正文

jQuery介绍+使用jQuery实现音乐播放

阅读提示:我把音乐播放代码放在了最后。

一、介绍

jQuery是一个快速、小巧且功能丰富的javaScript库,可以简化HTML文档遍历、事件处理、动画和Ajax交互等任务,当然随着javaScript的框架的起来jQuery 的使用有所减少,但在简单的场景中还是被广泛使用。

二、引入

 2.1 CND引入

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

2.2下载并引入

1、官网:jQuery

2、点击下载

3、引入

3.1 下载并引入:我这里用的是第一个,将源码全选(ctrl+A),复制粘贴(ctrl+C,ctrl+V)到自己项目中的文件中。

这里以防大家看不懂,我做一下解释

  • 第一个是未被压缩的开发版,便于大家学习和理解。
  • 第二个是用于调试压缩后的代码。
  • 第三个是jQuery更新的内容,主要修复 UI 渲染问题和内部方法兼容性。

4、效果

    三、语法

    3.1基本语法

    $(selector).action()

    $:这是jQuery的别名,代表的是相对应的库。

    selector:是表示选择的html的元素

    action():这是对选择的元素执行的操作,如.css()、.html()、.click()……

    3.2选择元素

    3.2.1 基本选择器

    //选择id
    $("#id_name");
    //选择类
    $(".class_name");
    //选择所有p元素
    $("p");

    3.2.2 层次选择器

    // 子元素选择器
    $("parent > child")  
    // 后代选择器
    $("ancestor descendant") 
    // 相邻兄弟选择器
    $("prev + next")
    // 兄弟选择器    
    $("prev ~ siblings") 

    3.3.3 过滤选择器

    $("li:first")      // 第一个li元素
    $("li:last")       // 最后一个li元素
    $("li:even")       // 偶数索引的li元素
    $("li:odd")        // 奇数索引的li元素
    $("li:eq(3)")      // 索引等于3的li元素
    $("li:gt(3)")      // 索引大于3的li元素
    $("li:lt(3)")      // 索引小于3的li元素

    3.3DOM操作

    3.3.1内容操作

    // 获取/设置文本内容
    $("#element").text()       // 获取文本
    $("#element").text("新文本") // 设置文本// 获取/设置HTML内容
    $("#element").html()       // 获取HTML
    $("#element").html("<b>新HTML</b>") // 设置HTML// 获取/设置表单值
    $("input").val()          // 获取值
    $("input").val("新值")     // 设置值

    演示一下: 

    <body><div class="box1">你好</div><div class="box2">天天开心</div><form><input type="text" placeholder="Name" name="name"><input type="password" placeholder="Password" name="password"></form><!-- 使用CDN引入jQuery --><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><script>console.log("Text:",$(".box1").text());   // 获取文本$(".box2").text("万事如意"); // 设置文本// 获取/设置HTML内容console.log("HTML:",$(".box1").html());       // 获取HTML$(".box2").html("<b>万事如意</b>"); // 设置HTML// 获取/设置表单值$("input[name='name']").val("张三"); // 设置名称console.log($("input[name='password']").val()); // 获取密码值$("input[name='password']").val("123456"); // 设置密码值</script>
    </body>

    3.3.2属性操作

    在操作前,我给box1添加了一些样式

    //属性操作//<img id="box3" src="图片1/tPkgLafP3r.jpg" alt="图片">console.log("alt:", $("#box3").attr("alt")); // 获取alt属性$("#box3").attr("src", "图片1/bgg.png")   // 设置src属性$("#box3").attr({                   // 设置多个属性"src": "图片1/bgg.png","alt": "新图片"});// 移除属性$("#box3").removeAttr("alt")console.log("alt:", $("#box3").attr("alt")); // 获取CSS属性// 类操作//<div id="div"></div>$("#div").addClass("highlight");    // 添加类$("#div").removeClass("highlight"); // 移除类$("#div").toggleClass("highlight"); // 切换类console.log("是否有highlight类:", $("#div").hasClass("highlight"));    // 检查是否有类

    3.3.3样式操作

    console.log("color:", $(".box1").css("color")); // 获取CSS$(".box1").css("color", "red"); // 设置CSS// 设置多个CSS样式$(".box1").css({"color": "red","font-size": "30px"j});

    3.3.4DOM事件

        //DOM事件// <button id="btn">点击</button>// 绑定事件$("#btn").click(function () {alert("按钮被点击");    //弹窗});// 简写事件$("#btn").on("click", function () {alert("按钮被点击");});// 事件委托/*<ol id="list"><li>sea</li><li>rode</li></ol>*/$("#list").on("click", "li", function () {alert($(this).text());});// 解绑事件$("#btn").off("click");// 一次性事件$("#btn").one("click", function () {alert("只触发一次");});// 常用事件$("#input").focus(function () { /* 获取焦点 */ });$("#input").blur(function () { /* 失去焦点 */ });$("#input").change(function () { /* 值改变 */ });$("#form").submit(function () { /* 表单提交 */ });$("#window").resize(function () { /* 窗口大小改变 */ });$("#window").scroll(function () { /* 滚动事件 */ });

    …… 

    3.4动画

    // 淡入淡出
    $("#box").fadeIn();
    $("#box").fadeOut();// 滑动效果
    $("#box").slideUp();
    $("#box").slideDown();// 自定义动画
    $("#box").animate({opacity: 0.5,left: "+=50px",
    }, 1000); // 1 秒完成动画

    3.5Ajax请求

    $.get("https://api.example.com/data", function(response) {console.log("获取数据成功:", response);
    });$.post("https://api.example.com/save", { name: "John" }, function(response) {console.log("提交成功:", response);
    });// 完整 Ajax 请求
    $.ajax({url: "https://api.example.com/data",method: "GET",dataType: "json",success: function(data) {console.log("数据加载成功:", data);},error: function(err) {console.error("请求失败:", err);}
    });

    四、音乐播放代码

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>音乐播放器</title><style>* {margin: 0;padding: 0;box-sizing: border-box;}body {font-family: 'Microsoft YaHei', sans-serif;background-color: #f5f5f5;display: flex;justify-content: center;align-items: center;min-height: 100vh;}.music-player {width: 300px;background-color: white;border-radius: 15px;box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);padding: 20px;text-align: center;}.song-info {margin-bottom: 20px;}.cover {width: 180px;height: 180px;border-radius: 50%;object-fit: cover;margin: 0 auto 15px;box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);animation: rotate 20s linear infinite;animation-play-state: paused;}.playing .cover {animation-play-state: running;}.song-name {font-size: 20px;font-weight: bold;margin-bottom: 5px;}.singer {font-size: 16px;color: #666;}.controls {display: flex;justify-content: center;align-items: center;gap: 20px;margin-top: 20px;}button {background: none;border: none;cursor: pointer;font-size: 18px;color: #333;width: 40px;height: 40px;border-radius: 50%;display: flex;justify-content: center;align-items: center;transition: all 0.3s;}button:hover {background-color: #f0f0f0;}.play-btn {width: 50px;height: 50px;background-color: #4CAF50;color: white;}.play-btn:hover {background-color: #45a049;}@keyframes rotate {from { transform: rotate(0deg); }to { transform: rotate(360deg); }}</style>
    </head>
    <body><div class="music-player"><div class="song-info"><img class="cover" src="" alt="封面"><div class="song-name">歌名</div><div class="singer">歌手</div></div><div class="controls"><button class="prev-btn">⏮</button><button class="play-btn">▶</button><button class="next-btn">⏭</button></div></div><audio class="audio-player"></audio><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><script>$(document).ready(function() {// 音乐数据let musicList = [];let currentIndex = 0;let isPlaying = false;const audio = $('.audio-player')[0];// 加载音乐数据$.ajax({type: "GET",url: "music.json",dataType: "json",success: function(data) {musicList = data;console.log("音乐数据加载成功:", musicList);loadMusic(currentIndex);},error: function(xhr, status, error) {console.error("加载音乐数据失败:", status, error);// 使用默认数据作为后备/*musicList = [{"name": "把回忆拼好给你","audio_url": "音乐/把回忆拼好给你.mp3","singer": "王贰浪","cover": "图片1/tPkgLafP3r.jpg"},{"name": "罗生门","audio_url": "音乐/罗生门.mp3","singer": "梨冻紧","cover": "图片1/bgg.png"}];*/loadMusic(currentIndex);}});// 加载音乐function loadMusic(index) {if (musicList.length === 0) return;const music = musicList[index];$('.song-name').text(music.name);$('.singer').text(music.singer);$('.cover').attr('src', music.cover);audio.src = music.audio_url;}// 播放/暂停音乐function togglePlay() {if (isPlaying) {audio.pause();$('.play-btn').text('▶');$('.music-player').removeClass('playing');} else {audio.play();$('.play-btn').text('⏸');$('.music-player').addClass('playing');}isPlaying = !isPlaying;}// 下一首function nextSong() {currentIndex = (currentIndex + 1) % musicList.length;loadMusic(currentIndex);if (isPlaying) {audio.play();}}// 上一首function prevSong() {currentIndex = (currentIndex - 1 + musicList.length) % musicList.length;loadMusic(currentIndex);if (isPlaying) {audio.play();}}// 事件监听$('.play-btn').click(togglePlay);$('.next-btn').click(nextSong);$('.prev-btn').click(prevSong);audio.addEventListener('ended', nextSong);});</script>
    </body>
    </html>

    music.json文件

    [{"name": "把回忆拼好给你","audio_url": "音乐/把回忆拼好给你.mp3","singer": "王贰浪","cover": "图片1/tPkgLafP3r.jpg"},{"name": "罗生门","audio_url": "音乐/罗生门.mp3","singer": "梨冻紧","cover": "图片1/bgg.png"}
    ]

    /*这是简化了的,我没有加进度条啥的,这里只是给大家一个参考。其实这个练手项目我在一个月前就完成了,但前几周一直有其它事情就耽搁了*/

    相关文章:

  1. Spring中Bean的作用域和生命周期
  2. 51c大模型~合集119
  3. win11离线安装donet3.5
  4. Linux中的信号量
  5. 【python】deepcopy深拷贝浅拷贝(结合例子理解)
  6. 3分钟极速部署MySQL:brew/apt/yum全平台一条龙实战
  7. 【计算机网络 | 第三篇】常见的网络协议(二)
  8. 数据结构实验7.1:二叉树的遍历
  9. WIN10重启开机不用登录,直接进入桌面
  10. Mysql insert一条数据的详细过程
  11. C语言求执行次数
  12. 【牛客练习赛137 C】题解
  13. 开发工具~
  14. Android音视频开发
  15. Vue.js核心功能实现
  16. 计算机视觉与深度学习 | TensorFlow基本概念与应用场景:MNIST 手写数字识别(附代码)
  17. Mamba模型时间序列预测
  18. Java创建对象的方式
  19. 中级软件设计师 - 知识点(附真题)目录大全
  20. 2025年4月19日-美团春招笔试题-第三题
  21. 广西大部气象干旱已达特旱
  22. 日媒:日本公明党党首将访华,并携带石破茂亲笔信
  23. 具象的“南方”|一个海南艺术家的穷困与信爱
  24. ESG领跑者|每一步都向前,李宁要让可持续发展成为可持续之事
  25. 马文化体验展商圈启动,环球马术冠军赛的能量不止在赛场
  26. 空山日落雨初收,来文徵明的画中听泉