jquery: how to change the size of a div from center
When I use jQuery animate() function to change the size of a div, it always begins from left-top point. How can I make it zoom from center instead from corner. For example, my code:
<div id="div1"></div>
<style>
#div1{
position: absolute;
width: 50px;
height: 50px;
background-color: red;
opa开发者_Python百科city: 0.4;
top: 40%;
left: 40%;
border-radius: 1000px;
margin: auto;
}
</style>
<script src="jquery.js"></script>
<script src="jquery.easing.1.3.js"></script>
<script>
$(document).ready(function(){
$("#div1").mouseover(function(){
$(this).animate(
{width: 100, height: 100, opacity: 1},
{duration: 500,
easing: "easeOutBounce"}
);
});
$("#div1").mouseout(function(){
$(this).animate(
{width: 50, height: 50, opacity: 0.4},
{duration: 500,
easing: "easeOutBounce"}
);
});
});
</script>
This will change from left-top point but I want it staring from center. Thanks!
Here is an example using @Schroedingers Cat's suggestion. I changed the top and left positions to pixel values rather than percentages.
JavaScript:
$("#div1").mouseover(function() {
$(this).animate({
width: 100,
height: 100,
top: 75,
left: 75,
opacity: 1
}, {
duration: 500,
easing: "easeOutBounce"
});
});
$("#div1").mouseout(function() {
$(this).animate({
width: 50,
height: 50,
top: 100,
left: 100,
opacity: 0.4
}, {
duration: 500,
easing: "easeOutBounce"
});
});
CSS:
#div1{
position: absolute;
width: 50px;
height: 50px;
background-color: red;
opacity: 0.4;
top: 100px;
left: 100px;
border-radius: 1000px;
margin: auto;
}
If you want to stay with percentages in your css, you can use the jQuery position()
function to get the top and left starting coordinates, along with width()
and height()
, and use these as the base values for your animation.
You can also get the initial settings from the css which you can use in the mouseOut
function.
jsfiddle example
精彩评论