1.使用HTML5的audio标签 (音频播放)
<audio id="click-sound">
<source src="audio/show.mp3" type="audio/mpeg">
</audio>
<button id="button">按钮</button>
var clickSound = document.getElementById("click-sound");
var button = document.getElementById("button");
button.addEventListener("click", function() {
clickSound.play();
});
2.使用HTML5的video标签(视频播放)
<video id="my-video" controls>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4">
</video>
var myVideo = document.getElementById("my-video");
// 播放视频
myVideo.play();
// 暂停视频
// myVideo.pause();
// 设置视频播放位置(单位:秒)
// myVideo.currentTime = 30;
// 设置视频音量(0-1之间的小数)
myVideo.volume = 0.5;
pause()方法可以暂停视频 currentTime属性可以设置视频播放位置 volume属性可以设置音量。
3.分类切换
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-3.6.1.js"></script>
<style>
#scroll-container {
width: 100%;
height: 30px;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
#scroll-content {
white-space: nowrap;
display: flex;
align-items: center;
padding: 0 20px;
}
.category {
flex: 0 0 auto;
margin-right: 20px;
padding: 5px 10px;
border-radius: 20px;
background-color: #f0f0f0;
cursor: pointer;
}
.category.active {
background-color: #007bff;
color: #fff;
}
</style>
<script src="js/jquery-3.6.1.js"></script>
</head>
<body>
<div id="scroll-container">
<div id="scroll-wrap">
<div id="scroll-content">
<div class="category">分类1</div>
<div class="category">分类2</div>
<div class="category">分类3</div>
<div class="category">分类4</div>
<div class="category">分类5</div>
<div class="category">分类6</div>
<div class="category">分类7</div>
<div class="category">分类8</div>
<div class="category">分类9</div>
<div class="category">分类10</div>
</div>
</div>
</div>
<script type="text/javascript">
var scrollContainer = $("#scroll-container");
var scrollWrap = $("#scroll-wrap");
var scrollContent = $("#scroll-content");
$("#scroll-content").on("click", ".category", function() {
var $this = $(this);
// 判断点击的是不是可见视图的最后一个标题
if ($this.is(":last-child")) {
// 将最后一个标题移动到开头
$this.prependTo($this.parent());
// 将内容滚动到用户可见的页面上,确保移动到开头的标题出现在可见视图中
var contentWidth = scrollContent.width();
var visibleWidth = scrollWrap.width();
var scrollLeft = scrollContent.scrollLeft();
if (scrollLeft > contentWidth - visibleWidth) {
scrollContent.scrollLeft(contentWidth - visibleWidth);
}
}
});
// 获取所有分类标题
var categories = $(".category");
// 给每个分类标题添加点击事件
categories.on("click", function() {
// 取消其他分类的选中状态
categories.removeClass("active");
// 选中当前分类,并滚动到它的位置
$(this).addClass("active");
var index = categories.index(this);
scrollContent.stop().animate({scrollLeft: index * (this.offsetWidth + 20)}, 500);
});
</script>
</body>
</html>