定位元素向下移动点击?

时间:2017-04-12 10:32:45

标签: jquery html css

我有一个绝对定位的div和一个按钮,可以使用jQuery切换转换。然而,当单击按钮时div会向下移动,我不希望它发生,我似乎无法找到导致它的原因,因为这在以前工作正常,定位元素在切换时不会移动。

可以通过删除topleft CSS属性来解决问题,但是div不会显示我想要的位置。

查看JSFiddle上的示例。

$('table').hide();
$('button').click(function() {
  $(this).siblings('table').toggle('show');
});
// TOGGLE ICON TRANSITION
$(function() {
  var icon = $('.dd-arrow');
  var button = $('.view-products');
  button.on('click', function() {
    $(this).closest('div').find('.dd-arrow').toggleClass('active').css('display', 'block');
    $(this).siblings('img').fadeToggle('fast');
  });
});
.prices {
  position: relative;
  display: inline-block;
}

.prices .dd-arrow {
  position: absolute;
  top: 50%;
  left: 50%;
  transition: all .5s ease-in-out 0s;
}

.prices .dd-arrow img {
  width: 20px;
}

.prices .dd-arrow.active {
  transform: rotate(360deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class="prices">
  <button class="view-products" onclick="swapText()">View Products:</button>
  <div class="dd-arrow"><img src="img/drop-down-arrow.svg" /></div>
  <table>
    <th>number</th>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </table>
</div>

2 个答案:

答案 0 :(得分:1)

请检查它是否有用。感谢。

$('table').hide();
$('button').click(function () {
  $(this).siblings('table').toggle('show');
});
// TOGGLE ICON TRANSITION
$(function () {
  var icon = $('.dd-arrow');
  var button = $('.view-products');
  button.on('click', function () {
    $(this).closest('div').find('.dd-arrow').toggleClass('active').css('display', 'block');
    $(this).siblings('img').fadeToggle('fast');
  });
});
    .prices {
        position: relative;
        display: inline-block;

        .dd-arrow {
            position: absolute;
            top: 0%;
            left: 0%;
            margin-left: 130px;
            margin-top: 30px;
            transition: all .5s ease-in-out 0s;
            img {
                width: 50px;
            }
        }
        .dd-arrow.active {
            transform: rotate(360deg);
        }

}
<div class="prices">
  <button class="view-products" onclick="swapText()">View Products:</button>
  <div class="dd-arrow"><img src="https://cdn.pixabay.com/photo/2017/04/06/16/57/auto-2208807_960_720.png"/></div>            
  <table>
    <th>number</th>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </table>
</div>

答案 1 :(得分:0)

有一些信息: 你把div放在百分比上。所以它是父div的百分比。在您的cas中,父div为<div class="prices">。 问题是,由于表格显示,当你点击按钮时这个div大小会增加。 因此,页面中的高度比较大,而且开始时的高度为50%。

有一个可行的解决方案:

    .prices {
    position: relative;
    display: inline-block;

    .dd-arrow {
        position: absolute;
        left: 50%;
        transition: all .5s ease-in-out 0s;
        img {
            width: 20px;
        }
    }
    .dd-arrow.active {
        transform: rotate(360deg);
    }

}