gpt4 book ai didi

javascript - 使用鼠标悬停和 Angular 更改多个元素

转载 作者:行者123 更新时间:2023-11-28 05:02:17 25 4
gpt4 key购买 nike

当鼠标悬停在 http://codepen.io/Feners4/pen/KggAwg 的立方体上时,如何让包装内的所有元素改变颜色?目前,我只能让它在鼠标悬停的一侧发生变化。为了学习目的,我想严格地使用 Angular 来做到这一点。

这是我的 HTML:

<html>

<header>
Angularity
</header>

<h1>hjskl</hi>

<body ng-app="App">
<div class="wrap">
<div class="cube"change-background colorcode=¨#f45642¨>
<div class="front" change-background>AAA</div>
<div class="back" change-background></div>
<div class="top" change-background></div>
<div class="bottom" change-background></div>
<div class="left" change-background></div>
<div class="right" change-background></div>
</div>
</div>

<div class="wrap2">
<div class="cube2">
<div class="front2" change-background colorcode=¨#f45642¨>AAA</div>
<div class="back2" change-background ></div>
<div class="top2" change-background></div>
<div class="bottom2" change-background></div>
<div class="left2" change-background></div>
<div class="right2" change-background></div>
</div>
</div>

</body>
</html>

这是我的 JS:

angular.module('App', [])
.directive('changeBackground', ['$animate', function($animate) {
return {
restrict: 'EA',
scope: {
colorcode: '@?'
},
link: function($scope, element, attr) {
element.on('mouseenter', function() {
element.addClass('change-color');
element.css('background-color', $scope.colorcode);
});
element.on('mouseleave', function() {
element.removeClass('change-color');
element.css('background-color', '@red');
});
}
};
}])

最佳答案

一种方法是将您的指令添加到立方体边的父级,然后在内部使用 .children() 将您的函数应用于每个子项。此外,您还希望您的类 change-color 具有通用性,因为没有 :foo,否则 CSS 仍将仅适用于悬停元素,即使它们全部上课了。

HTML

<div class="wrap">
<div class="cube" change-background colorcode=¨#f45642¨>
<div class="front" >AAA</div>
<div class="back" ></div>
<div class="top" ></div>
<div class="bottom" ></div>
<div class="left" ></div>
<div class="right" ></div>
</div>
</div>

<div class="wrap2">
<div class="cube2" change-background>
<div class="front2" colorcode=¨#f45642¨>AAA</div>
<div class="back2"></div>
<div class="top2"></div>
<div class="bottom2"></div>
<div class="left2"></div>
<div class="right2"></div>
</div>
</div>

JS

  link: function($scope, element, attr) {
element.on('mouseenter', function() {
element.children().addClass('change-color');
element.children().css('background-color', $scope.colorcode);
});
element.on('mouseleave', function() {
element.children().removeClass('change-color');
element.children().css('background-color', '@red');
});
}

CSS

.change-color {
color: #fff;
background-color: #f45642;
cursor: pointer;
}

Pen Example

关于javascript - 使用鼠标悬停和 Angular 更改多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40031909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com