当点击某个div时,我试图以编程方式将div置于另一个div下面。我尝试了一切无济于事,所以我需要一些帮助。下面是我写的代码。这是我想要做的http://jsfiddle.net/U3pVM/18656/
的jsfiddle链接<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<div class="box" ng-click="do($event)">
<p> HEY THERRE </p>
</div>
<div class="box2" ng-show="show">
</div>
</div>
</div>
function TodoCtrl($scope) {
$scope.show =false;
$scope.do = function(evt) {
var $this = $(evt.target);
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var centerX = offset.left ;
var centerY = offset.top + height;
$('.box2').css({
'position': 'absolute',
'top': centerY,
'left': centerX
});
$scope.show = !$scope.show;
console.log(evt);
console.log(centerX, centerY);
};
}
答案 0 :(得分:4)
在position: relative
元素上使用.box2
。另外,添加margin: 0 auto;
将其水平放置在中心位置。
这将减少用于定位元素的JS代码。
function TodoCtrl($scope) {
$scope.show = false;
$scope.do = function(evt) {
$scope.show = !$scope.show;
};
}
.box {
top: 10px;
right: 400px;
width: 150px;
height: 150px;
background: orange;
color: white;
z-index: 10;
margin: 0 auto;
}
.box2 {
position: relative;
width: 300px;
height: 150px;
background: green;
opacity: 1;
z-index: 9;
margin: 0 auto;
}
.box2.ng-hide-add {
transition: all linear 5.5s;
}
.box2.ng-hide {
opacity: 0;
}
.box2 {
animation: slideDown .5s;
}
@keyframes slideDown {
0% {
transform: translateY(-20%);
}
100% {
transform: translateY(0%);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<div class="box" ng-click="do($event)">
<p>HEY THERRE</p>
</div>
<div class="box2" ng-show="show"></div>
</div>
</div>
您也可以按照以下步骤删除控制器:
.box {
top: 10px;
right: 400px;
width: 150px;
height: 150px;
background: orange;
color: white;
z-index: 10;
margin: 0 auto;
}
.box2 {
position: relative;
width: 300px;
height: 150px;
background: green;
opacity: 1;
z-index: 9;
margin: 0 auto;
}
.box2.ng-hide-add {
transition: all linear 5.5s;
}
.box2.ng-hide {
opacity: 0;
}
.box2 {
animation: slideDown .5s;
}
@keyframes slideDown {
0% {
transform: translateY(-20%);
}
100% {
transform: translateY(0%);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app>
<h2>Todo</h2>
<div>
<div class="box" ng-init="show=false" ng-click="show=!show">
<p>HEY THERE</p>
</div>
<div class="box2" ng-show="show"></div>
</div>
</div>