gpt4 book ai didi

javascript - 如何删除这个循环来单独调用div元素?

转载 作者:行者123 更新时间:2023-11-28 03:58:38 25 4
gpt4 key购买 nike

这是我用于音频播放器的代码:

https://codepen.io/katzkode/pen/ZbxYYG

它的作用:

使用循环为每首歌曲一次创建多个音频播放器(通过使用单个 div 元素)。

循环:

/* createAudioElements
* create audio elements for each file in files */
function createAudioElements() {
for (f in files) {
var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"http://www.alexkatz.me/codepen/music/" + files[f] + "\"></audio>";
$("#audio-players").append(audioString);
}
}

/* createAudioPlayers
* create audio players for each file in files */
function createAudioPlayers() {
for (f in files) {
var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
$("#audio-players").append(playerString);
}
}

var 文件:

var files = ["interlude.mp3", // 0
"chooseyourweapon.mp3", // 1
"interlude.mp3", // 2
"scriptures.mp3" // 3
];

当我使用时在 HTML 中调用:

<div id="audio-players"></div>

我想要实现的目标:

删除循环,以便我可以单独插入任何播放器并单独调整它们,但我想要这样:https://puu.sh/ynD4q/6ab2ba7816.png

我想使用此代码来调用所需的音频播放器:

<audio id="audio-0" class="audio" preload="true">
<source src="http://www.alexkatz.me/codepen/music/interlude.mp3">
</audio>
<div id="audioplayer-0" class="audioplayer">
<button id="playbutton-0" class="play playbutton"></button>
<div id="timeline-0" class="timeline">
<div id="playhead-0" class="playhead"></div>
</div>
</div>

当我尝试使用它时,播放/停止/更改位置按钮停止工作。

这让我发疯,我刚刚开始学习 jQuery。 非常感谢!

最佳答案

files 数组更改为 settings 对象,并使用 elementIdsrc 为每个文件添加对象属性:

var settings = [
{"elementId" : "audio-player-1", "src" : "http://www.alexkatz.me/codepen/music/interlude.mp3"},
{"elementId" : "audio-player-2", "src" : "http://www.alexkatz.me/codepen/music/chooseyourweapon.mp3"},
{"elementId" : "audio-player-3", "src" : "http://www.alexkatz.me/codepen/music/scriptures.mp3"}
];

它非常有用,因为您可以添加任何您想要的属性。通过 src 属性,您可以从任何允许的网站添加音频文件。

然后在createAudioElements中将新的src属性设置为settings[f].src

随后在createAudioElementscreateAudioPlayers函数中将选择器名称(循环中收集的行添加到其中)更改为从相关elementId动态生成的 属性$("#"+ files[f].elementId)

// Event listener for DOM
document.addEventListener("DOMContentLoaded", theDOMHasLoaded, false);

// array of audio files (stored in a folder called music)
var settings = [{
"elementId": "audio-player-1",
"src": "http://www.alexkatz.me/codepen/music/interlude.mp3"
},
{
"elementId": "audio-player-2",
"src": "http://www.alexkatz.me/codepen/music/chooseyourweapon.mp3"
},
{
"elementId": "audio-player-3",
"src": "http://www.alexkatz.me/codepen/music/scriptures.mp3"
}
];

///////////////////////////////////////////////
// Find and store audio info
///////////////////////////////////////////////

// array for AudioObjects
var audioList = [];
// components and the index for their AudioObject
var componentDict = {};
// store AudioObject that is currently playing
var playingAudio = null;
// store playhead id if one is being dragged
var onplayhead = null;

/* AudioObject Constructor */
function AudioObject(audio, duration) {
this.audio = audio;
this.id = audio.id;
this.duration = duration;
}
/* bindAudioPlayer
* Store audioplayer components in correct AudioObject
* num identifes correct audioplayer
*/
AudioObject.prototype.bindAudioPlayer = function(num) {
this.audioplayer = document.getElementById("audioplayer-" + num);
this.playbutton = document.getElementById("playbutton-" + num);
this.timeline = document.getElementById("timeline-" + num);
this.playhead = document.getElementById("playhead-" + num);
this.timelineWidth = this.timeline.offsetWidth - this.playhead.offsetWidth
}

/* addEventListeners() */
AudioObject.prototype.addEventListeners = function() {
this.audio.addEventListener("timeupdate", AudioObject.prototype.timeUpdate, false);
this.audio.addEventListener("durationchange", AudioObject.prototype.durationChange, false);
this.timeline.addEventListener("click", AudioObject.prototype.timelineClick, false);
this.playbutton.addEventListener("click", AudioObject.prototype.pressPlay, false);
// Makes playhead draggable
this.playhead.addEventListener('mousedown', AudioObject.prototype.mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}

/* populateAudioList */
function populateAudioList() {
var audioElements = document.getElementsByClassName("audio");
for (i = 0; i < audioElements.length; i++) {
audioList.push(
new AudioObject(audioElements[i], 0)
);
audioList[i].bindAudioPlayer(i);
audioList[i].addEventListeners();
}
}

/* populateComponentDictionary()
* {key=element id : value=index of audioList} */
function populateComponentDictionary() {
for (i = 0; i < audioList.length; i++) {
componentDict[audioList[i].audio.id] = i;
componentDict[audioList[i].playbutton.id] = i;
componentDict[audioList[i].timeline.id] = i;
componentDict[audioList[i].playhead.id] = i;
}
}

///////////////////////////////////////////////
// Update Audio Player
///////////////////////////////////////////////

/* durationChange
* set duration for AudioObject */
AudioObject.prototype.durationChange = function() {
var ao = audioList[getAudioListIndex(this.id)];
ao.duration = this.duration;
}

/* pressPlay()
* call play() for correct AudioObject
*/
AudioObject.prototype.pressPlay = function() {
var index = getAudioListIndex(this.id);
audioList[index].play();
}

/* play()
* play or pause selected audio, if there is a song playing pause it
*/
AudioObject.prototype.play = function() {
if (this == playingAudio) {
playingAudio = null;
this.audio.pause();
changeClass(this.playbutton, "playbutton play");
}
// else check if playing audio exists and pause it, then start this
else {
if (playingAudio != null) {
playingAudio.audio.pause();
changeClass(playingAudio.playbutton, "playbutton play");
}
this.audio.play();
playingAudio = this;
changeClass(this.playbutton, "playbutton pause");
}
}

/* timelineClick()
* get timeline's AudioObject
*/
AudioObject.prototype.timelineClick = function(event) {
var ao = audioList[getAudioListIndex(this.id)];
ao.audio.currentTime = ao.audio.duration * clickPercent(event, ao.timeline, ao.timelineWidth);
}

/* mouseDown */
AudioObject.prototype.mouseDown = function(event) {
onplayhead = this.id;
var ao = audioList[getAudioListIndex(this.id)];
window.addEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
ao.audio.removeEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
}

/* mouseUp EventListener
* getting input from all mouse clicks */
function mouseUp(e) {
if (onplayhead != null) {
var ao = audioList[getAudioListIndex(onplayhead)];
window.removeEventListener('mousemove', AudioObject.prototype.moveplayhead, true);
// change current time
ao.audio.currentTime = ao.audio.duration * clickPercent(e, ao.timeline, ao.timelineWidth);
ao.audio.addEventListener('timeupdate', AudioObject.prototype.timeUpdate, false);
}
onplayhead = null;
}

/* mousemove EventListener
* Moves playhead as user drags */
AudioObject.prototype.moveplayhead = function(e) {
var ao = audioList[getAudioListIndex(onplayhead)];
var newMargLeft = e.clientX - getPosition(ao.timeline);

if (newMargLeft >= 0 && newMargLeft <= ao.timelineWidth) {
document.getElementById(onplayhead).style.marginLeft = newMargLeft + "px";
}
if (newMargLeft < 0) {
playhead.style.marginLeft = "0px";
}
if (newMargLeft > ao.timelineWidth) {
playhead.style.marginLeft = ao.timelineWidth + "px";
}
}

/* timeUpdate
* Synchronizes playhead position with current point in audio
* this is the html audio element
*/
AudioObject.prototype.timeUpdate = function() {
// audio element's AudioObject
var ao = audioList[getAudioListIndex(this.id)];
var playPercent = ao.timelineWidth * (ao.audio.currentTime / ao.duration);
ao.playhead.style.marginLeft = playPercent + "px";
// If song is over
if (ao.audio.currentTime == ao.duration) {
changeClass(ao.playbutton, "playbutton play");
ao.audio.currentTime = 0;
ao.audio.pause();
playingAudio = null;
}
}

///////////////////////////////////////////////
// Utility Methods
///////////////////////////////////////////////

/* changeClass
* overwrites element's class names */
function changeClass(element, newClasses) {
element.className = newClasses;
}

/* getAudioListIndex
* Given an element's id, find the index in audioList for the correct AudioObject */
function getAudioListIndex(id) {
return componentDict[id];
}

/* clickPercent()
* returns click as decimal (.77) of the total timelineWidth */
function clickPercent(e, timeline, timelineWidth) {
return (event.clientX - getPosition(timeline)) / timelineWidth;
}

// getPosition
// Returns elements left position relative to top-left of viewport
function getPosition(el) {
return el.getBoundingClientRect().left;
}
///////////////////////////////////////////////
// GENERATE HTML FOR AUDIO ELEMENTS AND PLAYERS
///////////////////////////////////////////////

/* createAudioElements
* create audio elements for each file in settings */
function createAudioElements() {
for (f in settings) {
var audioString = "<audio id=\"audio-" + f + "\" class=\"audio\" preload=\"true\"><source src=\"" + settings[f].src + "\"></audio>";
$("#" + settings[f].elementId).append(audioString);
}
}

/* createAudioPlayers
* create audio players for each file in settings */
function createAudioPlayers() {
for (f in settings) {
var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\">" +
"</button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
$("#" + settings[f].elementId).append(playerString);
}
}

/* theDOMHasLoaded()
* Execute when DOM is loaded */
function theDOMHasLoaded(e) {
// Generate HTML for audio elements and audio players
createAudioElements();
createAudioPlayers();

// Populate Audio List
populateAudioList();
populateComponentDictionary();
}
.audioplayer {
width: 480px;
height: 60px;
margin: 50px auto auto auto;
border: solid;
}

.playbutton {
height: 60px;
width: 60px;
border: none;
float: left;
outline: none;
}

.play {
background: url('http://www.alexkatz.me/codepen/img/play.png');
}

.pause {
background: url('http://www.alexkatz.me/codepen/img/pause.png');
}

.play,
.pause {
background-size: 50% 50%;
background-repeat: no-repeat;
background-position: center;
}

.timeline {
width: 400px;
height: 20px;
margin-top: 20px;
float: left;
border-radius: 15px;
background: rgba(0, 0, 0, .3);
}

.playhead {
width: 18px;
height: 18px;
border-radius: 50%;
margin-top: 1px;
background: rgba(0, 0, 0, 1);
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>player 1</h3>
<div id="audio-player-1"></div>
<h3>player 2</h3>
<div id="audio-player-2"></div>
<h3>player 3</h3>
<div id="audio-player-3"></div>

关于javascript - 如何删除这个循环来单独调用div元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com