我在 AngularJS 网络项目中。
我想在单击 anchor 链接时突出显示 div
。结构如下:
<div interaction-list-item="" sfinx-interaction="interaction" class="ng-isolate-scope">
...
<a name="iid_7923"></a>
...
</div>
并且 anchor 链接在点击时将 location.hash
设置为类似的,因此 URL 可能如下所示:http://localhost:9000/#/home#iid_7923
。这个iid_
是动态的,在_
我已经尝试了几种 jQuery 解决方案,但最终代码非常丑陋和冗长:
$(".indicator.active.line-D").click(function () {
// more similar code..
if ($("div:contains('D4')") && $("a:contains('D4')")) {
$(".col-md-6.interactionscol:contains('D4')").css("border", "3px solid #428bca");
setTimeout(function () {
$(".col-md-6.interactionscol:contains('D4')").css("border", "");
}, 1000);
}
// more similar code..
});
此代码段的目的是在单击 anchor lnik 时,检查 div 和 anchor 是否相互匹配,然后将 CSS 应用到其上,并在 1 秒后将其删除。
如果 location.hash
包含例如 #iid_7923
和带有 a 标签< 的
哪个名字相同,高亮显示!div
,我怎么能做得更聪明
我就是想不通。提前致谢。
更新:我想实现类似这样的:target selector
但是我的 anchor 代码与经典方式不相似..它看起来像这样:
$scope.scrollToInteraction = function (iid) {
$location.hash(iid);
$anchorScroll();
};
最佳答案
使用 Angular,使用 $rootScope
在 Controller 或整个应用程序中公开您的散列:
angular.module('foo').run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.currentHash = function() {
return $location.hash();
};
}]);
然后在您的 html 中使用一个指令来设置您的 div 的样式:
<div data-ng-class="{'active': currentHash() == 'iid_7923'}">
注意 currentHash() 中缺少的 #
。
关于javascript - 如果子元素名称与 location.hash 匹配,则突出显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31157852/