简体   繁体   中英

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

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

Why not use :focus in CSS?

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.

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

Instead of using JS for this, use the CSS pseudo-class :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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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