如何从弹出窗口中获取复选框值以使其更改页面的 CSS?



每个人。基本上,这个流媒体网站以16:9显示4:3的视频,忽略了纵横比,使它们都被拉伸了。我检查了一下,视频是预拉伸的,因为它们的分辨率是1024x576。

尽管如此,我还是找到了一种使它们为4:3的方法,即将transform: scaleX(0.75)添加到类playkit-container中。

为了让事情变得更容易,我正在尝试制作一个简单的Chrome扩展,它带有一个带有复选框的弹出窗口。如果选中该复选框,则javascript应将transform: scaleX(0.75)添加到playkit-container。如果未选中,则应重置CSS或将其设置为transform: scaleX(1.0)

这是我的:

extension.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Opto AR Fixer</h1>
<p>Fixes the AR of 4:3 episodes streaming on Opto.</p>
<input type="checkbox" name="forcear" id="forcear">
<label for="forcear">Force 4:3</label>
<script src="extension.js"></script>
</body>
</html>

扩展.js

var popup = chrome.extension.getViews({type:"popup"})[0];
var checkBox = popup.document.getElementById("forcear").addEventListener("click", myFunction);
function myFunction() {  
if (checkBox.checked == true){
document.getElementsByClassName("playkit-container")[0].style.transform = "scaleX(0.75)"
} else {
document.getElementsByClassName("playkit-container")[0].style.transform = "scaleX(1.0)"
}
}

然而,什么也没发生。如果我检查弹出窗口并检查日志,每当我单击按钮时,它都会向我抛出以下错误:Uncaught TypeError: Cannot read property 'checked' of undefined

Uncaught TypeError: chrome.extension.getViews is not a function

我在这里错过了什么?

这意味着属性"checked"的所有者未定义。当您定义checkBox时,您将其分配给.addEventListener((,该函数不返回任何内容。因此,这意味着checkBox被指定为"未定义"。

在这种情况下,您将希望将变量分配拆分为元素本身,然后单独分配偶数侦听器。

例如

var popup = chrome.extension.getViews({type:"popup"})[0];
var checkBox = popup.document.getElementById("forcear");
checkBox.addEventListener("click", myFunction);
function myFunction() {  
if (checkBox.checked == true){
document.getElementsByClassName("playkit-container")[0].style.transform = "scaleX(0.75)"
} else {
document.getElementsByClassName("playkit-container")[0].style.transform = "scaleX(1.0)"
}
}

在页面循环中查找el:

function findEl() {
setTimeout((){ 
const el = document.getElementsByClassName("playkit-container")[0];
if (el.length > 0) {
// do other logic once el is found if needed
} else {
findEl();
}
}, 1000);
}

最新更新