未捕获的类型错误无法读取未定义的属性“style”
2020-09-07
4406
我尝试通过单击按钮来修改图像。 js 应该在单击按钮时更新图像样式,但它会出错。 但是当我在控制台上尝试相同操作时,它可以正常工作。
这是我的 HTML 代码
<!DOCTYPE html>
<html>
<head>
<title>Image Modifier</title>
<style>
body{
display: flex;
justify-content: center;
align-items: center;
}
img{
width: 50%;
filter: initial;
}
</style>
</head>
<body>
<img id="pic" src="nature.jpg">
<button id="contrast" onclick="cont()">Contrast</button>
<button id="grayscale" onclick="gray()">Grayscale</button>
<button id="invert" onclick="inv()">Invert</button>
<script type="text/javascript">
var image = document.getElementById('pic')
function cont(image) {
image.style.filter="contrast(180%)";
}
function gray(image) {
image.style.filter="grayscale(100%)";
}
function inv(image) {
image.style.filter="invert(100%)";
}
</script>
</body>
</html>
它给出了以下错误
Uncaught TypeError: Cannot read property 'style' of undefined
at cont (first.html:26)
at HTMLButtonElement.onclick (first.html:19)
cont @ first.html:26
onclick @ first.html:19
Uncaught TypeError: Cannot read property 'style' of undefined
at gray (first.html:29)
at HTMLButtonElement.onclick (first.html:20)
gray @ first.html:29
onclick @ first.html:20
Uncaught TypeError: Cannot read property 'style' of undefined
at inv (first.html:32)
at HTMLButtonElement.onclick (first.html:21)
2个回答
问题在于,您向每个函数传递了一个
image
变量,但该变量并不存在,因此返回未定义
var image = document.getElementById('pic')
function cont() {
image.style.filter = "contrast(180%)";
}
function gray() {
image.style.filter = "grayscale(100%)";
}
function inv() {
image.style.filter = "invert(100%)";
}
body {
display: flex;
justify-content: center;
align-items: center;
}
img {
width: 50%;
filter: initial;
}
<img id="pic" src="https://static.passeportsante.net/680x357/i93408-.jpeg">
<button id="contrast" onclick="cont()">Contrast</button>
<button id="grayscale" onclick="gray()">Grayscale</button>
<button id="invert" onclick="inv()">Invert</button>
Alexandre Elshobokshy
2020-09-07
尝试使用 const 而不是 var
const image = document.getElementById('pic')
或者在每个函数内使用“let”定义变量
function cont(image) {
let image = document.getElementById('pic')
image.style.filter = "contrast(180%)";
}
function gray(image) {
let image = document.getElementById('pic')
image.style.filter = "grayscale(100%)";
}
function inv(image) {
let image = document.getElementById('pic')
image.style.filter = "invert(100%)";
}
Davide
2020-09-07