简体   繁体   English

如何通过使用JavaScript更改CSS值来​​移动/放置DIV容器?

[英]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容器作为块,它们具有固定的宽度,可能还有高度和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我需要以某种方式将margin-top (或padding-top )应用于容器.two以便当鼠标悬停在.one时将其移动几个像素以下,而当您将鼠标指针放在一边时, .two出现回到原来的位置。

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

second div must be followed by first div 第二个div后面必须是第一个div

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

If some other element present between one and two, try this. 如果一两个元素之间存在其他元素,请尝试此操作。

For your javascript (jQuery) solution: 对于您的javascript(jQuery)解决方案:

$( ".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 添加了一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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