javascript - jQuery - CSS - 函数 - 尝试更改当前标签的类

标签 javascript jquery html css addclass

我会快速简单地说明这一点:

这是我的 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');

}}

我想要实现的是向 videoMuteUnmute/videoPlayPause 添加类来更改背景图像,以显示不同阶段的不同图标静音/未静音/< strong>播放/暂停 唯一有用的是控件。但不改变类。

最佳答案

通过 $(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 获得正确的元素,然后相应地更改其类。

注意:

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

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>

这将为您解决问题。

关于javascript - jQuery - CSS - 函数 - 尝试更改当前标签的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31907637/

相关文章:

javascript - sw 预缓存 - 从不同域加载 Assets 的运行时缓存

javascript - 渲染带有 alpha channel 的 png 时, Three.js 会从显卡中泄漏像素

javascript - 根据混淆后的js调整html的onClick调用

html - 我怎样才能拥有没有来自父 div 的背景图像的子 div

javascript - 有没有可靠的解决方案可以在 HTML 页面中自动播放背景音乐?

javascript - 用于获取 javascript 中特定嵌套元素的正则表达式

javascript - 缩放不同宽度的图像以适合一行并保持相同的高度

javascript - 统计 HTML 表中唯一值的实例

javascript - JQuery链接打开新窗口

javascript - Internet Explorer 不剪切溢出的内容