javascript - jquery 在加载页面时向所有元素添加 .active 类

标签 javascript jquery html css

我正在创建一个 jquery 网络播放器。

我的问题是当页面加载 #playlist 中的歌曲标题时有一个.active类(class)。还有更多 <div id="audio-info">部分显示播放列表中所有歌曲的数据。

但是当我从播放列表中选择一首歌曲时,一切正常,事件歌曲采用 .active类和 #audio-info仅显示事件歌曲的信息。

我不确定为什么这在页面加载时无法正常工作。 有人可以看一下代码并指导我吗?

错误可能与 js $('#playlist li').removeClass('active'); element.addClass('active'); 中的这段代码有关

这是一个片段

$(document).ready(function() {
  var audio;
  //Hide pause
  $('#pause').hide();

  initAudio($('#playlist li:first-child'));

  function initAudio(element) {
    var song = element.attr('song');
    var title = element.text();
    var artist = element.attr('artist');

    // Audio Object

    audio = new Audio('media/' + song);
    //insert audio info
    $('.artist').text(artist);
    $('.title').text(title);
    console.log(audio);
    $('#playlist li').removeClass('active');
    element.addClass('active');
  }

  // play button
  $('#play').click(function() {
    audio.play();
    $('#play').hide();
    $('#pause').show();
    showDuration();
  });

  //Pause button

  $('#pause').click(function() {
    audio.pause();
    $('#play').show();
    $('#pause').hide();
  });

  //Next button
  $('#next').click(function() {
    audio.pause();
    var next = $('#playlist li.active').next();
    if (next.length == 0) {
      next = $('#playlist li:first-child');
    }
    initAudio(next);
    audio.play();
    showDuration();
  });


  $('#playlist li').click(function() {
    audio.pause();
    initAudio($(this));
    $('#play').hide();
    $('#pause').show();
    audio.play();
    showDuration();
  });
  //volume control

  $('#volume').change(function() {
    audio.volume = parseFloat(this.value / 100);

    console.log(audio.volume);
  });

  //Time/showDuration

  function showDuration() {
    $(audio).bind('timeupdate', function() {
      //Get Hours and minutes
      var s = parseInt(audio.currentTime % 60);
      var m = parseInt(audio.currentTime / 60) % 60;
      if (s < 10) {
        s = '0' + s;
      }
      $('#duration').html(m + ':' + s);
      var value = 0;
      if (audio.currentTime > 0) {
        value = Math.floor((100 / audio.duration) * audio.currentTime);
      }
      $('#progress').css('width', value + '%');
    });
  };

  var promise = audio.play();

  if (promise !== undefined) {
    promise.then(_ => {
      // Autoplay started!
    }).catch(error => {
      // Autoplay was prevented.
      // Show a "Play" button so that user can start playback.
    });
  }

});
/*************Player ******/

.clearfix {
  clear: both;
}

.audio-player {
  margin-top: 20px;
  margin-bottom: 20px;
}

.progressbar-container {
  display: inline-flex;
  width: 100px;
  margin: 0;
  position: relative;
  top: 7px;
}

.progress-bar {
  background-color: #c2002d !important;
}

#audio-info {
  text-align: center;
  background-color: lightgrey;
  color: #c2002d;
}

input#volume {
  width: 95%;
  margin-left: 2%;
  -webkit-appearance: none !important;
  background: #ccc;
  height: 1px;
  margin-bottom: 20px;
}

input#volume::-webkit-slider-thumb {
  -webkit-appearance: none !important;
  background: url(/uploads/images/player//knobred.png) no-repeat center center;
  background-size: 10px 10px;
  width: 10px;
  height: 10px;
  cursor: pointer;
}

#buttons {
  width: 15%;
  display: block;
  /*margin: 15px auto;*/
  /*margin-left: 23px;*/
  /* overflow: auto;*/
}

button#play {
  width: 20px;
  height: 20px;
  background: url(/uploads/images/player/play.svg) no-repeat center center;
  background-size: 15px 15px;
  border: none;
}

button#pause {
  width: 20px;
  height: 20px;
  background: url(/uploads/images/player/pause.svg) no-repeat center center;
  background-size: 15px 15px;
  border: none;
}


/*button#prev{
width: 20px;
height: 20px;
background: url(../images/rev.svg) no-repeat center center;
background-size: 15px 15px;
}*/

#tracker {
  position: relative;
  width: 5%;
}

#playlist {
  padding-inline-start: 0px !important;
}

#playlist li {
  list-style: none;
  cursor: pointer;
}

.active {
  color: #c2002d;
}

#playlist>li>img {
  height: 15px;
  float: right;
  margin-top: 5px;
  cursor: pointer;
}

a>img {
  height: 15px;
  float: right;
  margin-top: 5px;
  cursor: pointer;
  display: inline-block;
}


/*.info-dot{
    height: 15px;
background: url(../images/player/info.svg) no-repeat center center;

cursor: pointer;
display: inline-block;
}*/


/************Player ends *********/
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-9">
      sfs
    </div>
    <div class="col-md-3">
      <div class="audio-player">
        <div id="audio-info">
          <span class="artist"></span> - <span class="title"></span>
        </div>
        <input id="volume" type="range" min="0" max="100" value="50">
        <br>
        <div id="buttons">
          <span>
          <!--  <button id="prev"> </button> -->
            <button id="play"></button>
            <button id="pause"></button>
          <!--   <button id="stop"></button>-->
          <!--   <button id="next"> >> </button>-->
          </span>
        </div>
        <div class="clearfix"></div>
        <div id="tracker">
          <div id="progress-bar" class="progress">
            <span id="progress" class="progress-bar" role="progressbar"></span>
          </div>
          <span id="duration"></span>
        </div>
        <div class="clearfix"></div>
        <ul id="playlist" class="hidden">
          <div class="d-flex flex-row">
            <div class="col-md-9">
              <li class="active" song="somesong.mp3" cover="cover1.jpg" artist="someartist">somesong.mp3</li>
            </div>
            <div class="col-md-3">
              <a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
                <img src="/images/player/info.svg"></a>
            </div>
          </div>

          <div class="d-flex flex-row">
            <div class="col-md-9">
              <li class="active" song="song2.mp3" cover="cover1.jpg" artist="someartist">song2.mp3</li>
            </div>
            <div class="col-md-3">
              <a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
                <img src="/images/player/info.svg"></a>
            </div>
          </div>
          <div class="d-flex flex-row">
            <div class="col-md-9">
              <li class="active" song="song3.mp3" cover="cover1.jpg" artist="someartist">song3.mp3</li>
            </div>
            <div class="col-md-3">
              <a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
                <img src="/images/player/info.svg"></a>
            </div>
          </div>

        </ul>
      </div>
    </div>
  </div>
  <!-- row -->
</div>
<!--Container -->

最佳答案

您目前使用 li:first-child,但由于每个 li 都有不同的父级,因此它们都是他们的 first-child各自的 parent 。使用 #playlist > div:first-child li

$(document).ready(function() {
  var audio;
  //Hide pause
  $('#pause').hide();

  initAudio($('#playlist > div:first-child li'));

  function initAudio(element) {
    var song = element.attr('song');
    var title = element.text();
    var artist = element.attr('artist');

    // Audio Object

    audio = new Audio('media/' + song);
    //insert audio info
    $('.artist').text(artist);
    $('.title').text(title);
    console.log(audio);
    $('#playlist li').removeClass('active');
    element.addClass('active');
  }

  // play button
  $('#play').click(function() {
    audio.play();
    $('#play').hide();
    $('#pause').show();
    showDuration();
  });

  //Pause button

  $('#pause').click(function() {
    audio.pause();
    $('#play').show();
    $('#pause').hide();
  });

  //Next button
  $('#next').click(function() {
    audio.pause();
    var next = $('#playlist li.active').next();
    if (next.length == 0) {
      next = $('#playlist li:first-child');
    }
    initAudio(next);
    audio.play();
    showDuration();
  });


  $('#playlist li').click(function() {
    audio.pause();
    initAudio($(this));
    $('#play').hide();
    $('#pause').show();
    audio.play();
    showDuration();
  });
  //volume control

  $('#volume').change(function() {
    audio.volume = parseFloat(this.value / 100);

    console.log(audio.volume);
  });

  //Time/showDuration

  function showDuration() {
    $(audio).bind('timeupdate', function() {
      //Get Hours and minutes
      var s = parseInt(audio.currentTime % 60);
      var m = parseInt(audio.currentTime / 60) % 60;
      if (s < 10) {
        s = '0' + s;
      }
      $('#duration').html(m + ':' + s);
      var value = 0;
      if (audio.currentTime > 0) {
        value = Math.floor((100 / audio.duration) * audio.currentTime);
      }
      $('#progress').css('width', value + '%');
    });
  };

  var promise = audio.play();

  if (promise !== undefined) {
    promise.then(_ => {
      // Autoplay started!
    }).catch(error => {
      // Autoplay was prevented.
      // Show a "Play" button so that user can start playback.
    });
  }

});
/*************Player ******/

.clearfix {
  clear: both;
}

.audio-player {
  margin-top: 20px;
  margin-bottom: 20px;
}

.progressbar-container {
  display: inline-flex;
  width: 100px;
  margin: 0;
  position: relative;
  top: 7px;
}

.progress-bar {
  background-color: #c2002d !important;
}

#audio-info {
  text-align: center;
  background-color: lightgrey;
  color: #c2002d;
}

input#volume {
  width: 95%;
  margin-left: 2%;
  -webkit-appearance: none !important;
  background: #ccc;
  height: 1px;
  margin-bottom: 20px;
}

input#volume::-webkit-slider-thumb {
  -webkit-appearance: none !important;
  background: url(/uploads/images/player//knobred.png) no-repeat center center;
  background-size: 10px 10px;
  width: 10px;
  height: 10px;
  cursor: pointer;
}

#buttons {
  width: 15%;
  display: block;
  /*margin: 15px auto;*/
  /*margin-left: 23px;*/
  /* overflow: auto;*/
}

button#play {
  width: 20px;
  height: 20px;
  background: url(/uploads/images/player/play.svg) no-repeat center center;
  background-size: 15px 15px;
  border: none;
}

button#pause {
  width: 20px;
  height: 20px;
  background: url(/uploads/images/player/pause.svg) no-repeat center center;
  background-size: 15px 15px;
  border: none;
}


/*button#prev{
width: 20px;
height: 20px;
background: url(../images/rev.svg) no-repeat center center;
background-size: 15px 15px;
}*/

#tracker {
  position: relative;
  width: 5%;
}

#playlist {
  padding-inline-start: 0px !important;
}

#playlist li {
  list-style: none;
  cursor: pointer;
}

.active {
  color: #c2002d;
}

#playlist>li>img {
  height: 15px;
  float: right;
  margin-top: 5px;
  cursor: pointer;
}

a>img {
  height: 15px;
  float: right;
  margin-top: 5px;
  cursor: pointer;
  display: inline-block;
}


/*.info-dot{
    height: 15px;
background: url(../images/player/info.svg) no-repeat center center;

cursor: pointer;
display: inline-block;
}*/


/************Player ends *********/
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-9">
      sfs
    </div>
    <div class="col-md-3">
      <div class="audio-player">
        <div id="audio-info">
          <span class="artist"></span> - <span class="title"></span>
        </div>
        <input id="volume" type="range" min="0" max="100" value="50">
        <br>
        <div id="buttons">
          <span>
          <!--  <button id="prev"> </button> -->
            <button id="play"></button>
            <button id="pause"></button>
          <!--   <button id="stop"></button>-->
          <!--   <button id="next"> >> </button>-->
          </span>
        </div>
        <div class="clearfix"></div>
        <div id="tracker">
          <div id="progress-bar" class="progress">
            <span id="progress" class="progress-bar" role="progressbar"></span>
          </div>
          <span id="duration"></span>
        </div>
        <div class="clearfix"></div>
        <ul id="playlist" class="hidden">
          <div class="d-flex flex-row">
            <div class="col-md-9">
              <li class="active" song="somesong.mp3" cover="cover1.jpg" artist="someartist">somesong.mp3</li>
            </div>
            <div class="col-md-3">
              <a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
                <img src="/images/player/info.svg"></a>
            </div>
          </div>

          <div class="d-flex flex-row">
            <div class="col-md-9">
              <li class="active" song="song2.mp3" cover="cover1.jpg" artist="someartist">song2.mp3</li>
            </div>
            <div class="col-md-3">
              <a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
                <img src="/images/player/info.svg"></a>
            </div>
          </div>
          <div class="d-flex flex-row">
            <div class="col-md-9">
              <li class="active" song="song3.mp3" cover="cover1.jpg" artist="someartist">song3.mp3</li>
            </div>
            <div class="col-md-3">
              <a data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">
                <img src="/images/player/info.svg"></a>
            </div>
          </div>

        </ul>
      </div>
    </div>
  </div>
  <!-- row -->
</div>
<!--Container -->

关于javascript - jquery 在加载页面时向所有元素添加 .active 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041320/

相关文章:

javascript - Grunt 首先连接目录递归文件

javascript - 在 angularjs 中运行 jquery 代码的最佳方式是什么?

javascript - 从 id 在 jquery 中那个 div 的最后一个外观中获取类名

javascript - 复选框不会在页面加载时触发函数

javascript - 解析错误 400(错误请求){代码 : 201, 消息: "missing user password"}

javascript - 根据 meteor 中的选定值从集合中填充选择字段并进行过滤

javascript - 多个 onClick 选择器到底是如何按时间顺序工作的?

javascript - 发送 JSON 到与资源不同的地址

javascript - 跨度文本更改的 MutationObserver 不会触发

html - Perl WWW Mechanize submit_form() 未指向请求的 form_number 如何解决?