<div class="div-0"></div>
<div class="div-1">
<button-class="test-button">test1</button>
<button-class="test-button">test2</button>
<button-class="test-button">test3</button>
</div>
<div class="div-2">
<button-class="test-button">test4</button>
<button-class="test-button">test5</button>
<button-class="test-button">test6</button>
</div>
<div class="div-3"></div>
我知道如何计算两个div之间的距离。
var disnace_new=$('.div-1').offset().top - $('.div-2').offset().top;
对于某些事件,我将增加margin-top属性.example
$(".test-button").on("click",function(){
$(".div-2").css("margin-top","new-value");
continue.......
});
在这里,我无法获得新的价值,也无法获得新的价值。在这种情况下,我想使两个div之间的距离为-10
怎么可能。
即$('.div-1').offset().top - $('.div-2').offset().top
设置为 -10
$('.div-1').offset().top - $('.div-1').offset().top =-10;
这可能吗?
答案 0 :(得分:2)
您可以尝试这样的事情:
var distance_new = $('.div-1').offset().top - $('.div-2').offset().top;
console.log(distance_new);
$(".test-button").on("click",function(){
$(".div-2").css("margin-top",distance_new+$('.div-1').outerHeight()+"px");
console.log($('.div-1').offset().top - $('.div-2').offset().top);
})
&#13;
* {
box-sizing:border-box;
}
.div-1 {
padding: 10px;
margin: 20px 0;
}
.div-2 {
padding: 10px;
margin: 30px 0;
}
.space {
height: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-0"></div>
<div class="div-1">
<button class="test-button">test1</button>
<button class="test-button">test2</button>
<button class="test-button">test3</button>
</div>
<div class="space"></div>
<div class="div-2">
<button class="test-button">test4</button>
<button class="test-button">test5</button>
<button class="test-button">test6</button>
</div>
<div class="div-3"></div>
&#13;