如何在HTML中显示按钮中的图像



嗨,我目前正在开发一个本地web服务器来控制我的车里的东西与RPi 4。我使用nodejs的npm express ejs和rpi-gpio库。

我想使用pgio电源继电器来控制的东西,如灯,led条,加热器等,所以我创建了按钮,但我想使用图像作为按钮而不是文本,当我试图改变src IDE可以找到图像并显示给我,但当我检查浏览器它找不到它

如果你也有建议来简化我的代码,我洗耳恭听

路径看起来像这样

/Projects/dbDash/package.json
/Projects/dbDash/server.js
/Projects/dbDash/public/200x200/theImage.png
/Projects/dbDash/views/index.ejs

server.js

const express = require('express')
const app = express()
var path = require('path');
var gpio = require('rpi-gpio');
app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'public')));
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res){
res.render('index',{status:"Press Button To change Status of Relay."});
});
app.listen(3000, function () {
console.log('Server Started on Port: 3000!')
})
app.post('/relay1/change', function(req, res){
gpio.read(7, function(err, theValue) {
if (err) throw err;
gpio.write(7, !theValue)
console.log("Written " + (!theValue?"true":"false") + " to pin 7");
return res.render('index', {status: (!theValue?"ON":"OFF")});
});
})

index.ejs

<div class="BorderMargin">
<form action="/relay1/change" method="post">
<button type="submit" class="button"><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
<button type="submit" formmethod="post" formaction="/relay2/change" class="button"><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
<button type="submit" formmethod="post" formaction="/relay3/change" class="button"><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
</form>
<form action="/relay4/change" method="post">
<button type="submit" class="button"><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
</form>
<a>Relay Status: <%=status %></a>
</div>

代码检查器

GET http://localhost:3000/public/200x200/hazard.png 404 (Not Found)

我不认为一个按钮标签可以显示图像。但是你可以做的是创建一个div并在里面放置你的图像标签,并相应地设置样式。

然后给div设置一个onClick属性它就会执行你想要的操作

如果你真的需要一个按钮,就把图像放在按钮里面…如果你按照布莱特博士说的那样去做,也会很好。

我所需要做的就是在server.js中添加这一行

app.use('/public', express.static(process.cwd() + '/public'))

感谢@YasirPoongadan的评论然后所有的按钮都显示一张图片

最新更新