HTML:
<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>
JS:
$scope.hoverIn = function(){
$scope.hoverEdit = true;
};
$scope.hoverOut = function(){
$scope.hoverEdit = false;
};
代码是荒谬的,因为我认为它太多了。我认为它可以简化。无论如何,结果切换所有项目一旦它被悬停。我有jQuery背景,所以我不知道如何使单个项目的工作在ng-repeat
.
Angular解决方案
你可以这样修改:
$scope.hoverIn = function(){
this.hoverEdit = true;
};
$scope.hoverOut = function(){
this.hoverEdit = false;
};
在ngMouseover(和类似的)函数中context是当前项作用域,所以它指的是当前子作用域。
你还需要把ngRepeat
放在li
上:
<ul>
<li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
{{task.name}}
<span ng-show="hoverEdit">
<a>Edit</a>
</span>
</li>
</ul>
演示strong>
<CSS解决方案/h3>
然而,如果可能的话,只尝试用CSS做这些事情,这将是最佳的解决方案,不需要JS:
ul li span {display: none;}
ul li:hover span {display: inline;}
我只需在ng-mouseover和ng-mouseleave;不需要麻烦js文件:)
<ul ng-repeat="task in tasks">
<li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
<span ng-show="hoverEdit"><a>Edit</a></span>
</ul>
我可能会把你的例子改成这样:
<ul ng-repeat="task in tasks">
<li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
<span ng-show="task.editable"><a>Edit</a></span>
</ul>
//js
$scope.enableEdit = function(item){
item.editable = true;
};
$scope.disableEdit = function(item){
item.editable = false;
};
我知道这是一个微妙的差异,但使域少绑定到UI操作。从心理上讲,它更容易让人想到一个项目是可编辑的,而不是鼠标在上面滑过。
jsFiddle例子。
这里有点晚了,但我发现这是一个值得自定义指令处理的常见问题。下面是它的样子:
.directive('toggleOnHover', function(){
return {
restrict: 'A',
link: link
};
function link(scope, elem, attrs){
elem.on('mouseenter', applyToggleExp);
elem.on('mouseleave', applyToggleExp);
function applyToggleExp(){
scope.$apply(attrs.toggleOnHover);
}
}
});
你可以这样使用:
<li toggle-on-hover="editableProp = !editableProp">edit</li>
这是一个只有CSS的例子。在示例中,我使用SASS和SLIM。
https://codepen.io/Darex1991/pen/zBxPxe苗条:
a.btn.btn--joined-state
span joined
span leave
SASS:
=animate($property...)
@each $vendor in ('-webkit-', '')
#{$vendor}transition-property: $property
#{$vendor}transition-duration: .3s
#{$vendor}transition-timing-function: ease-in
=visible
+animate(opacity, max-height, visibility)
max-height: 150px
opacity: 1
visibility: visible
=invisible
+animate(opacity, max-height, visibility)
max-height: 0
opacity: 0
visibility: hidden
=transform($var)
@each $vendor in ('-webkit-', '-ms-', '')
#{$vendor}transform: $var
.btn
border: 1px solid blue
&--joined-state
position: relative
span
+animate(opacity)
span:last-of-type
+invisible
+transform(translateX(-50%))
position: absolute
left: 50%
&:hover
span:first-of-type
+invisible
span:last-of-type
+visible
border-color: blue