第二次单击时,元素将移动到屏幕边缘

时间:2016-05-24 02:58:49

标签: javascript jquery html css

我有一个div,在我点击一个元素(button1)后,展开它的高度。然后我出现另一个按钮,允许你缩小div(button2)。单击button1后,div展开,button2显示在底部。然后我可以单击button2将div缩小回正常,但是如果我再次展开div,则button2现在离屏幕边缘,尽管位于相同的底部位置,只是最左边而不是居中。

我必须将button2上的边距设置为-25px,因为绝对定位是偏离中心的。而且我需要使用绝对定位,因为看起来只有这样才能让按钮在扩展后出现在div的底部。

$(".button1").on("click", function(){

  $(".button1" ).fadeOut(200);	

  $("#block3").animate({ 
    height: '800px' 
  }, 600, function() {

    $(".button2").fadeIn(200);

  });

});



$(".button2").on("click", function(){

  $(".button2").fadeOut(200);		
  $("#block3").animate({ 
    height: '400px' 
  }, 600,function(){
    $(".button1" ).fadeIn(200);

  });

});
.button2{
  width: 50px;
  height: 50px;
  display:none; 
  position: absolute;
  margin-left: 25px;
}

.button1{

width: 50px;
height: 50px;
margin-top: 25px;
image-rendering: auto;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row">
  <div class = "col-md-12" id = "block3">
      <img src="https://placehold.it/120x80/00aaaa/fff/?text=scroll.png"  class = "button1" />
      <img src="https://placehold.it/120x80/00aaaa/fff/?text=scroll1.png"  class = "button2" />
  </div>
</div>

上传代码。

https://jsfiddle.net/bs9xhe5e/2/

3 个答案:

答案 0 :(得分:3)

在第二次单击时,它更改了内联样式以显示:block而不是display:inline,如果你只是将display:inline添加到你的jQuery中就可以了;

https://jsfiddle.net/havL1z3m/

$(".button2").css({display:"inline"});

答案 1 :(得分:0)

.button2一直显示在左侧的原因是absolute定位为其left提供了默认0px

最简单的解决方法可能是删除absolute位置以及margin-left。相反,要将.button2放到该部分的底部,只需设置margin-top: 725px

.button2{
  width: 50px;
  height: 50px;
  display:none; 
  margin-top: 725px;
}

然后您将不再需要使用.css()来更改bottom的{​​{1}}。

看看这个工作小提琴:https://jsfiddle.net/gkpx7L15/

答案 2 :(得分:0)

更改按钮2样式,如下所示:

.button2{
    width: 50px;
    height: 50px;
    display:none; 
    position: absolute;
    margin-left: -25px;
   left:50%;//added style
}

https://jsfiddle.net/bs9xhe5e/3/ 一切都会好起来的 注意:只有当像这里一样固定宽度时,元素将被定位到父级的中心。例如:

.someItem{
  width: someWidth;//here we set some width to element
  left: 50%; //Here we set position from the left
  margin-left: -(somewidth/2);//here we set -half of the element's width for margin-left
}
相关问题