javascript - 使用JS更改输入字段的背景颜色
问题描述
我试图在 JS 中聚焦时更改输入字段的背景颜色,当它没有聚焦时,它应该只是白色背景颜色。
我已经尝试过这段代码,但是得到了一个错误,所以我不确定我做错了什么。
function navn(obj, evt) {
if (evt.type == "focus")
style.background = "yellow"; //<--what is style?
else if (evt.type == "blur") {
style.background = "white";
}
}
<form>
<fieldset>
<legend>Personlige oplysninger</legend>
<div>
<label for="navn">Udfyld dit fornavn:</label>
<input type="text" name="navn" class="navn" id="navn" value="" onclick="navn()" placeholder="Dit fornavn" />*
<span id="obsnavn" class="alert"></span>
</div>
<input type="button" value="Send" id="send" />
</fieldset>
</form>
解决方案
您的代码中有几个问题:
- 您的处理程序函数将参数声明
obj
为第一个参数。触发事件时,处理函数中声明的第一个元素是对事件对象的引用。 - 您正在尝试对
blur
or做出反应focus
,但您正在onclick
HTML 标记上使用。 - 要更改元素的背景颜色,您需要修改它的
style
对象以及该style
对象中的backgroundColor
属性(background-color
CSS 属性的 JavaScript 等效项)。
这是一个涉及addEventListener
功能的解决方案。它允许您将相同的侦听器附加到两个事件:blur
和focus
。
var element = document.getElementById("navn");
element.addEventListener("focus", handler);
element.addEventListener("blur", handler);
function handler(evt) {
if (evt.type == "focus")
evt.target.style.backgroundColor = "yellow"; //<--what is style?
else if (evt.type == "blur") {
evt.target.style.backgroundColor = "white";
}
}
<form>
<fieldset>
<legend>Personlige oplysninger</legend>
<div>
<label for="navn">Udfyld dit fornavn:</label>
<input type="text" name="navn" class="navn" id="navn" value="" placeholder="Dit fornavn" />*
<span id="obsnavn" class="alert"></span>
</div>
<input type="button" value="Send" id="send" />
</fieldset>
</form>
推荐阅读
- spring - 如何允许原始 HttpServletRequest 使用 Spring Boot Security 处理登录
- postgresql - 使用终端命令的 golang-migrate 未知驱动程序 postgresql
- java - Android 以编程方式存储的图像在 PC 上具有无效格式
- c# - 比较这两个集合的最快方法是什么?
- r - 如何避免 rowSums() 删除行名?
- java - 获取数据时 json 解析速度慢
- javascript - 使用 Javascript 三元运算符将 CSS 类添加到 HTML
- powerbi - Power BI - 使用切片器过滤表以在连接列中匹配
- c# - Moq - 将参数从 setup() 传递给 return()
- c# - ASP.NET Core 3.0 ConfigureApplicationCookie 在 ConfigureServices 之外