开发者

Slow transition to hover state with Javascript

I am working on css in which when mouse hovers on images, it g开发者_开发问答ets bigger. e.g.

#image-div img { width:100px; height:100px;}
#image-div:hover img { width:200px; height:200px;}

Now i want it to be animated a little. Like it shall zoom in slowly, and on mouse out, it shall zoom out slowly. Please help.

Note: I am not very well familiar with javascript.


These animations are typically done with Javascript. Rather than writing the Javascript by hand, it is probably easier to use the jQuery library, which includes the ".animate()" method. The animate method requires you give the destination css properties as parameters, like so:

(Since you wrote you are not familiar with Javascript, I've included everything you need to include the jQuery library)

<script src="http://www.google.com/jsapi" type="text/javascript"></script>

<script type="text/javascript">google.load("jquery", "1.6.4");</script>

<script type="text/javascript">

    $(document).ready(function(){

        $("#image-div img").live({mouseenter:myfin,
              mouseleave:myfout});

    });
    function myfin () {
    $(this).animate({height: 200, width: 200},1000); //1000 = 1 second animation
}
function myfout () {
    $(this).animate({height: '', width: ''},1000); //1000 = 1 second animation
    //setting the height and width to '' will clear the inserted style, leaving you with your original style
}
</script>

Then all you should need is to set the height and width to 100px in your CSS, and remove the #image-div:hover definition.

If you would like to animate using class definitions in your CSS file, you can do so using a jQuery plug-in. See the following question for help on that:

jQuery.animate() with css class only, without explicit styles


If you don't need to support older browsers you could use the CSS3 transition attribute. It does not require any javascript and works on Safari, Firefox, and Opera. http://www.w3schools.com/css3/css3_transitions.asp

#image-div img {
    width:100px;
    height:100px;
    transition:all 1s ease-in-out
    -moz-transition:all 1s ease-in-out;
    -webkit-transition:all 1s ease-in-out;
    -o-transition:all 1s ease-in-out;
}
#image-div:hover img {
    width:200px;
    height:200px;
}


Look into the .animate() method and pair it with .hover(). This will allow you to apply a specific transition when the mouse is hovered over a specific element, in this case zoom, as desired.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜