简体   繁体   中英

How to fade in a specific CSS property

I want to fade in a border color from grey to red on an element on focus.

Getting the color to change immediately is easy, but I want it to fade in slowly.

HTML

<input class="timeBlock destination hours" 
    type="text" 
    name="desHours" 
    value="00" 
    maxlength="2">

CSS

input.timeBlock {
    height: 90px;
    width: 90px;
    text-align: center;
    font-size: 3.5em;
    border-radius: 10px;
    color: #444;
    border: 3px solid #ccc;
    box-shadow: 0px 0px 10px rgba(0,0,0,0.15) inset; 
    position: absolute;
    top:0;
    bottom: 0;
    margin: auto;
}

input.focus {
    border: 3px solid #cc0000;
}

JS

$("input").focus(function() {
    $(this).fadeIn('slow', function(){
       $(this).addClass('focus');
  });
});     

You don't need to use JavaScript to achieve this. The CSS3 transition property is very useful:

input {
    border: 3px solid #ccc;
    transition:border 1s;
}
input:focus {
    border: 3px solid #cc0000;
}

See working example .

A little side note: bear in mind they've worked for a long time in Chrome and Firefox, but IE<9 won't support them . You'll still get a change in border color, but no transition.

With jQuery, you could add a class to your html element with method addClass and fade it in.

HTML:

<input class="penguin"></input>

CSS:

.foobar {
    transition:border 1s;
    border: 38px solid #cc0000;
}

JavaScript:

$(".penguin").focus(function() {
  $(this).fadeIn('slow', function(){
    $(this).addClass('foobar');
  });
});

Demo: http://jsfiddle.net/ecj6Q/2/

When the input field receives focus the first time, it fades in as it adds the class foobar to any tags with class penguin. The result is the border slowly increases in size from 0px to 38px over 1 second.

http://jsfiddle.net/c6WcR/

Using Jquery UI

$("input").focus(function() {
$(this).animate({borderColor: "#ff0000" });
}); 

Example of a CSS text effect fading in.

HTML:

<div id="penguin">Skipper</div>

CSS:

#penguin {
    height: 90px;
    width: 250px;
    font-size: 3.5em;
    color: blue;
    box-shadow: 0px 0px 10px rgba(0,0,0,0.15) inset; 
}
#penguin:hover {
    text-shadow: green 0 0 5px;
    transition:text-shadow 1s;
}

Demo Fiddle: http://jsfiddle.net/Gbuk6/4/

When you hover over the div, the text fades in and flares out. When you stop hovering, it fades out back to where it was.

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