[英]Change background color of input field using 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
或focus
做出反应,但您在HTML标签上使用了onclick
。 style
对象,并在此style
对象中修改backgroundColor
属性(JavaScript等效于background-color
CSS属性)。 这是涉及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>
因为您的函数是参数,所以当您在不带参数的情况下调用onclick =“ navn()”时,它将无法正常工作
这样称呼它:
onblur="blur(this)" onfocus="focus(this)"
function blur(obj) {
obj.style.backgroundColor == "white";
}
function focus(obj) {
obj.style.backgroundColor = "yellow";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.