javascript - 未捕获的类型错误无法读取未定义的属性“样式”
问题描述
我正在尝试使用按钮单击来修改图像。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)
解决方案
问题是您将一个image
变量传递给每个不存在的函数,因此返回 undefined
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>
推荐阅读
- powerbi - 根据参数从另一个表中复制值
- python - 索引 0 处的 QTreeWidgetItem.insertChild
- bash - 带头的 xargs -n
- flutter - 颤振会为图像使用缓存吗?
- reactjs - React-router-dom 嵌套路由不适用于 ProtectedRoute/PrivateRoute
- javascript - reactjs - redux 表单和材质 ui 框架 - 自动完成字段
- javascript - 在香草/纯 JS 中无限滚动而不会产生间隙
- python - 如何在 while 循环中更新 ODE 的方程
- c# - 如何使用单独的通知内容向多个用户发送 Firebase
- javascript - 创建表格形式 JSON