首页 > 解决方案 > 如何使用 js 选择器选择“::cue”元素并更改它?我正在尝试创建一个按钮来更改字幕不透明度

问题描述

那是我确定提示的css文件。我想创建一个按钮,以便用户可以更改当前字幕轨道的不透明度和字体大小。

    <style>
    ::cue {
      font-size: 20px;
      font-family: Georgia, serif;
      color: blue;
      background-position: right;
      opacity: 1;
    }
    </style>

标签: javascripthtmlcss

解决方案


任何 JS 都无法选择伪元素,但有一个实际可行(绝对不是很好)的解决方案:

<script>
var head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');
head.appendChild(style);


// call the below function in your event handler, 
// and pass the 'style' object to it, and the required opacity:

// example: by clicking a button the opacity will be set to 0.6
const button = document.querySelector('button');
button.addEventListener("click", function(){ 
    doFormatting(style, 0.6)
});



function doFormatting(objStyle, opacity){
    if (objStyle.styleSheet){
      // maybe unnecessary, but this is required for IE8 and below.
      objStyle.styleSheet.cssText = "::cue{opacity:"+opacity+"}";
    } else {
     objStyle.innerHTML = "::cue{opacity:"+opacity+"}"
    }
}
</script>

推荐阅读