jQuery - CSS - 功能 - 尝试更改当前标签的 class

jQuery - CSS - function - Trying to change class of current tag

关于这个我会简单快速:

这是我的 HTML

<div id="headerVideoControls" class="overlayElement">
  <div id="videoMuteUnmute" onclick="muteUnmuteVideo('headerVideo')">mute button</div>
</div>

已编辑

<video id="headerVideo" loop muted preload="auto" poster="css\img\headerVideoPreview.jpg">
  <source src="uploads/video/headerVideo_2.mp4" type="video/mp4"> 
</video> 

这是我的 jQuery

function muteUnmuteVideo(id) { 
      activeVideo = document.getElementById(id);
if (activeVideo.muted) {
    activeVideo.muted = false;
    $(this).addClass('unMuted'); 
} else {
    activeVideo.muted = true;  
    $(this).addClass('muted');

}}

我想要实现的是将 class 添加到更改背景图像的 videoMuteUnmute/videoPlayPause 中,以显示不同阶段的不同图标 mute/ 未静音/正在播放/已暂停 唯一有用的是控件。但不改变 class.

试试如果(activeVideo.muted == true)

muteUnmuteVideo 函数中的 this 关键字有问题。

您的 muteUnmuteVideo 函数是在全局范围内定义的。当您使用 event attributes 例如 onclick 时,发生的是在该范围内调用该函数,这意味着 this 关键字引用 Window 对象。基本上它与在事件处理程序之外调用它没有什么不同,它只是按照定义的方式执行函数。您有对 event 的引用,但 this 将指向 Window 对象。

您有几个选择,第一个是使用 event.target 而不是 thisevent 将引用被单击的元素。像这样:

    $(event.target).addClass('unMuted');

或者,您可以使用 addEventListener 而不是 onclick attribute,这是推荐的,因为它使您的布局和行为分开,这通常是更好的方法。这样,this 将引用被单击的元素。像这样:

    document.getElementById('videoMuteUnmute').addEventListener('click', muteUnmuteVideo)

您还可以定义元素的 onclick 属性,然后 this 将引用该元素。像这样:

    document.getElementById('videoMuteUnmute').onclick = muteUnmuteVideo

此外,您可能想在当前设置中使用 toggleClass,一旦您点击按钮,您将始终拥有两个 类,因为它们永远不会被删除。

$(this) 你没有引用 currentVideo 对象,使用下面的代码:

function muteUnmuteVideo(id) { 
   activeVideo = $("#"+id);
   if (activeVideo.muted) {
      activeVideo.muted = false;
      activeVideo.addClass('unMuted'); 
   } else {
      activeVideo.muted = true;  
      activeVideo.addClass('muted');
}}

使用 $("#"+id) 您将通过 id 获得正确的元素,然后相应地更改其 class。

注:

如果你只使用 addClass() 而没有删除它,你可能同时拥有 mutedunMuted class,所以最好使用 .attr("class", ...) :

function muteUnmuteVideo(id) {
  var activeVideo = $("#" + id);
  if (activeVideo.attr("muted") == "true") {
    activeVideo.attr("muted", "false");
    activeVideo.attr("class", "unMuted");
    alert("unMuted");
  } else {
    activeVideo.attr("muted", "true");
    activeVideo.attr("class", "muted");
    alert("Muted");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="headerVideoControls" class="overlayElement">
  <div id="videoMuteUnmute" onclick="muteUnmuteVideo('headerVideo')">mute button</div>
</div>

<video id="headerVideo" loop muted preload="auto" poster="css\img\headerVideoPreview.jpg">
  <source src="uploads/video/headerVideo_2.mp4" type="video/mp4">
</video>

这对你有用。