使用JQuery动态重新定位元素

时间:2015-10-15 02:01:30

标签: javascript jquery html css

我试图让选定元素的对应位置在相关元素的顶部但是我想确保“底部”元素低于所选元素而不是它下面。如果你看一下这个例子,你就会明白我的意思。

半工作代码示例:

$('.wrapper-2').on('click', '[class^="unique"]', function(e) {

  var selected = '#' + $(this).attr('class');

  $('.wrapper-1>div').each(function() {
    $(this).css({
      'background-color': 'orange',
      'position': 'relative'
    });
  });

  console.log($(selected).position());

  $(selected).css({
    'background-color': 'blue',
    'position': 'absolute',
    'top': '0px'
  });

});
.wrapper {
    font-family: Arial;
    font-size: 12px;
    color: #FFF;
}
.wrapper-1 {
    position: absolute;
    top: 0px;
}
.wrapper-2 {
    margin: 0 auto;
    width: 140px;
}
.wrapper-1 div {
    position: relative;
    width: 120px;
    height: 50px;
    background-color: orange;
    margin: 10px;
}
.wrapper-2 div {
    position: relative;
    text-align: center;
    width: 120px;
    height: 50px;
    background-color: grey;
    margin: 10px;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper wrapper-1">
  <div id="unique1">One</div>
  <div id="unique2">Two</div>
  <div id="unique3">Three</div>
  <div id="unique4">Four</div>  
</div>

<div class="wrapper wrapper-2">
  <div class="unique1">- 1 -</div>
  <div class="unique2">- 2 -</div>
  <div class="unique3">- 3 -</div>
  <div class="unique4">- 4 -</div>
</div>

更新FIDDLE THAT WORKS

1 个答案:

答案 0 :(得分:2)

一种简单的方法是在容器顶部添加填充,以填充列表中第一个元素将占用的空间。其他人将像以前一样坐在它下面:

&#13;
&#13;
$('.wrapper-2').on('click', '[class^="unique"]', function(e) {

  var selected = $('#' + $(this).attr('class'));

  $('.wrapper-1>div').each(function() {
    $(this).css({
      'background-color': 'orange',
      'position': 'relative'
    });
  });

  console.log(selected.position());

  selected.css({
    'background-color': 'blue',
    'position': 'absolute',
    'top': '0px'
  });

  // ** this is the new bit
  //
  $('.wrapper-1').css('padding-top', '60px');
});
&#13;
.wrapper {
  font-family: Arial;
  font-size: 12px;
  color: #FFF;
}
.wrapper-1 {
  position: absolute;
  top: 0px;
}
.wrapper-2 {
  margin: 0 auto;
  width: 140px;
}
.wrapper-1 div {
  position: relative;
  width: 120px;
  height: 50px;
  background-color: orange;
  margin: 10px;
}
.wrapper-2 div {
  position: relative;
  text-align: center;
  width: 120px;
  height: 50px;
  background-color: grey;
  margin: 10px;
  cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper wrapper-1">
  <div id="unique1">One</div>
  <div id="unique2">Two</div>
  <div id="unique3">Three</div>
  <div id="unique4">Four</div>
</div>

<div class="wrapper wrapper-2">
  <div class="unique1">- 1 -</div>
  <div class="unique2">- 2 -</div>
  <div class="unique3">- 3 -</div>
  <div class="unique4">- 4 -</div>
</div>
&#13;
&#13;
&#13;