Jquery slide animation

2019-08-03 22:23发布

问题:

Good day!

I am trying to hide and show divs with slide animation. My code is as follows:

<style> 
    div.bigBox
            {
            background-color:white;
            width:100px;
            height:125px;
            overflow:hidden;
            }
            div.try{
            background-color:green;
            width:100px;
            height:125px;
            float: left;
            }
            div.try2{
            background-color:yellow;
            width:100px;
            height:125px;
            }
    }   
  </style> 
  <script language="JavaScript" src="js/jquery-1.6.1.js"></script>
  <script src="http://ui.jquery.com/latest/ui/jquery.effects.core.js"></script>
  <script src="http://ui.jquery.com/latest/ui/jquery.effects.slide.js"></script>
</head> 
<body> 
    <div class="bigBox">
          <div class="try">
              <p id="haha">CLICK THIS</p>
              <p>This is a demonstration of jQuery SimpleDialog.</p>
          </div>
          <div class="try2">
              <h3 id="test2">CLICK THIS</h3>
              <p>This is a demonstration of jQuery SimpleDialog.</p>
          </div>
    </div>
<script> 
    $('#haha').click(function () {  
      alert("test");
      $('.try').hide("slide", { direction: "left" }, 1000);
      $('.try2').show("slide", { direction: "right" }, 1000);
    }); 
</script> 

The problem is the transition of one box to another. It doesn't flow very smoothly. I want to hide and at the same time show (like tailing the box to be hidden). Please help. Thanks

回答1:

There are probably a dozen ways to skin this cat, but here's what I did:

  • Gave the bigBox position: relative
  • Changed the try boxes to use position: absolute so that they stack on top of one another
  • Changed the order of the HTML to make sure try (not try2) stays on top; you could do this other ways like with z-index
  • Removed overflow: hidden on bigBox and made background transparent, although that shouldn't honestly make a difference
  • Changed the CSS to suit my personal style; sorry, it's a semi-OCD thing

Fiddle: http://jsfiddle.net/GregP/CV7fd/1/

I didn't methodically test my theory, but I THINK it was the floating that was causing your problem.

No point showing the "switching the order of the .try and .try2 boxes" markup or the JavaScript (which is untouched), but here's the updated CSS:

div.bigBox {
  background-color:transparent;
  width:100px;
  height:125px;
  position: relative;
}

.try, .try2{
  width:100px;
  height:125px;
  position: absolute;
}

.try {
  background-color:green; 
}

.try2{
  background-color:yellow;
}

(shoot, could've used the width: and height: on bigBox, too. Ah well, you get the point, no need for me to be pedantic!)



回答2:

Have you considered having both elements in a single div (which would be partially visible) and just slide it by changing margins, padding or however you implement it?