HTML, CSS and jQuery: Making an Auto-Playing Music Player
Music players are one of the common elements in modern web design. This article will introduce how to use HTML, CSS and jQuery to create an automatically playing music player, and provide specific code examples.
First, create a container containing the music player in the HTML file:
<div class="music-player"> <audio id="myAudio"> <source src="music.mp3" type="audio/mpeg"> </audio> <button id="playButton">播放</button> <button id="pauseButton">暂停</button> </div>
In the above code, we create an audio using the <audio>
tag player, and set the src
attribute to the URL of the music file. Next, we added two buttons, one to play music and another to pause it.
Next, we need to use CSS styles to beautify the music player:
.music-player { text-align: center; } button { padding: 10px 20px; background: #333; color: #fff; border: none; border-radius: 5px; margin: 10px; cursor: pointer; }
The above CSS styles center-align the music player container and set the background color, text color and other styles of the button. Attributes.
Now, we use jQuery to implement the function of the music player:
$(document).ready(function(){ var audio = document.getElementById("myAudio"); $("#playButton").click(function(){ audio.play(); }); $("#pauseButton").click(function(){ audio.pause(); }); });
In the above JavaScript code, we use the document.getElementById()
method to get the audio element , and assign it to a variable. We then trigger the play and pause functionality of the audio by clicking the button.
Finally, we put the above HTML, CSS and jQuery code in an HTML file and introduce the jQuery library:
<!DOCTYPE html> <html> <head> <title>自动播放的音乐播放器</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> /* CSS代码 */ </style> </head> <body> <div class="music-player"> <!-- HTML代码 --> </div> <script> // JavaScript代码 </script> </body> </html>
In the above code, remember to paste the CSS code into <style></style>
tag, paste the JavaScript code into the <script></script>
tag, and paste the previously mentioned HTML code into the music player container.
Through the above steps, we successfully created an automatically playing music player made using HTML, CSS and jQuery. When the user clicks the play button, the music will start playing; when the user clicks the pause button, the music will stop playing.
Hope this article can help you understand how to create an auto-playing music player using HTML, CSS and jQuery.
The above is the detailed content of HTML, CSS and jQuery: Make an auto-playing music player. For more information, please follow other related articles on the PHP Chinese website!