简体   繁体   English

如何使用javascript更改输入的样式?

[英]How to change style of an input with javascript?

I want to give a 我想给一个

-webkit-box-shadow:inset 0 0 5px black;

property to a text box as one focuses on it. 属性作为文本框的焦点。

For example, here the background-color is being changed, but I want box-shadow instead. 例如,这里的背景色正在更改,但我想改用盒子阴影。

<script>
function myFunction(x)
{
x.style.background="yellow";
}
</script>

and the HTML 和HTML

<input type="text" onfocus="myFunction(this)">

Why not use :focus in CSS? 为什么不在CSS中使用:focus?

http://jsfiddle.net/VjLKV/ http://jsfiddle.net/VjLKV/

input {
    border: 1px solid black;
}

input:focus {
    outline: none;
    border: 1px solid black;
    -webkit-box-shadow:inset 0 0 5px black;
}

Define css classes, and you can easily switch them as needed. 定义css类,您可以根据需要轻松切换它们。

<script>
function myFunction(x)
{
x.style.className="yourcssclass";
}
</script>

Instead of using JS for this, use the CSS pseudo-class :focus : 除了使用JS之外,还可以使用CSS伪类:focus

input[type="text"]:focus
{
    -webkit-box-shadow:inset 0 0 5px black;
    box-shadow:inset 0 0 5px black;
}

That way, the textbox will get the shadow when the user tabs into it, or clicks it, or whatever - and the styles will properly go away when they leave, and so on. 这样,当用户在其中单击或单击文本框时,该文本框将获得阴影-样式在离开时将正确消失,依此类推。

Remember to use the unprefixed version of the box-shadow style as well. 切记也要使用框阴影样式的无前缀版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM