简体   繁体   中英

How to move/position DIV container by changing CSS values using Javascript?

I got two div containers as blocks with some fixed width and maybe height and display: block;

<div class="one"></div>
<div class="two"></div>

When you hover your mouse over container .one I need somehow to apply margin-top (or padding-top ) to container .two so it moves couple pixels below while mouse is over .one and when you move mouse pointer aside, .two comes back to it's original position.

.one:hover + .two
 {
   margin-top: 2px;
 }

second div must be followed by first div

.one:hover ~ .two
 {
   margin-top: 2px;
 }

If some other element present between one and two, try this.

For your javascript (jQuery) solution:

$( ".one" ).hover(
  function() {
     $('.two').css('marginTop', '5px');
 }, function() {
     $('.two').css('marginTop', '0');
 });

For smoother movement:

$( ".one" ).hover(
  function() {
     $('.two').animate({
         marginTop: "5px"
      }, 500 );
 }, function() {
     $('.two').animate({
         marginTop: "0"
      }, 500 );
 });

Added a Demo

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