通过按钮使div浮动进出

时间:2016-10-20 09:39:50

标签: javascript html css

我遇到问题,让我的div从右边漂到50%的屏幕,我似乎无法弄清楚为什么它不会工作。



myFunction = function() {
  var divPosition = $(".FadeIn").offset();
  alert("Position: " + divPosition.left);
  if (divPosition.right < '200%') {
    $(".FadeIn").animate({
      right: '50%'
    }, 1000);
  } else {
    $(".FadeIn").animate({
      right: '100%'
    }, 1000);
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="button" class="btn btn-primary" name="FadeButton" value="Lees meer..." onclick="myFunction()" />
</div>
<div class="FadeIn">
  Test
</div>
&#13;
&#13;
&#13;

它应该从右边漂到中间(恰好是50%),但它根本不做什么。我无法弄清楚原因。

https://jsfiddle.net/mbqxch2d/1/

3 个答案:

答案 0 :(得分:1)

试试这个

完整工作示例JS-Fiddle

如果用户点击外侧和关闭按钮也包括在内。如果我错过了什么,请写评论。

如果您还想要一个以垂直为中心的框,只需更新我的动画:

$moreSocialsContainer.fadeIn().animate({
  right: '50%',
  'margin-right': (((1 - $moreSocialsContainer.outerWidth(true)) + 1) / 2) + 'px',
  top: '50%',
  'margin-top': (((1 - $moreSocialsContainer.outerHeight(true)) + 1) / 2) + 'px'
});

答案 1 :(得分:0)

您必须将元素的CSS位置属性设置为relative,fixed或absolute以操纵或动画其位置。例如,您可以将以下属性添加到div元素:style =&#34; position:absolute;&#34;。然后,使用window innerWidth属性将元素浮动到屏幕中间。

 <script type="text/javascript">
    function myFunction() {


        $(".FadeIn").animate({
            left: this.innerWidth / 2
        }, 1000);

    }
</script>

答案 2 :(得分:0)

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script> 
function showhide(){
    $("#move").toggleClass("move"); 
}; 
</script> 
<style> 
body {
    overflow: hidden;
}
.move {
    width: 300px;
    height: 100px;
    background-color: red;
    position: absolute;
    -webkit-animation-name: animate;
    -webkit-animation-duration: 1s;
    -webkit-animation-delay: 0.1s;
    animation-name: animate;
    animation-duration: 1s;
    animation-delay: 0.1s;  
    right:-50%;
    animation-iteration-count: 1;
    animation-fill-mode: forwards; 
} 
@-webkit-keyframes animate {
    0%   {right-50%;transform: translate(-50%, 0);}     
    100% {right: 50%;transform: translate(50%, 0);} 
} 
@keyframes animate {
    0%   {right-50%;transform: translate(-50%, 0);}
    100% {right: 50%;transform: translate(50%, 0);} 
}

</style> 
</head> 
<body>

<div id="move"></div>

<button onclick="showhide()">Click to Show</button>

</body> 
</html>