Javascript 如果子元素名称与location.hash匹配,则突出显示div
我在一个AngularJS网络项目中 我想在单击锚链接时突出显示一个Javascript 如果子元素名称与location.hash匹配,则突出显示div,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我在一个AngularJS网络项目中 我想在单击锚链接时突出显示一个div。结构如下: <div interaction-list-item="" sfinx-interaction="interaction" class="ng-isolate-scope"> ... <a name="iid_7923"></a> ... </div> 这个片段的目的是,在单击锚定lnik时,检查div和锚定是否相互匹配,然后将CSS应用到它上,并在1秒后将其
div
。结构如下:
<div interaction-list-item="" sfinx-interaction="interaction" class="ng-isolate-scope">
...
<a name="iid_7923"></a>
...
</div>
这个片段的目的是,在单击锚定lnik时,检查div和锚定是否相互匹配,然后将CSS应用到它上,并在1秒后将其删除
如果
location.hash
包含例如#iid_7923
和带有标记的div
,则突出显示它
我就是搞不懂。提前谢谢
更新:我想实现类似的目标:
但是我的锚代码与经典的方式不同。。看起来是这样的:
$scope.scrollToInteraction = function (iid) {
$location.hash(iid);
$anchorScroll();
};
可以使用事件将类添加到父元素
var lastParent = null;
window.addEventListener('hashchange', function() {
// Remove class from previous target parent
if(lastParent)
{
lastParent.className = (' '+lastParent.className+' ').replace(' hastarget ',' ');
lastParent = null;
}
// Remove the '#' from the location hash
var targetId = document.location.hash.substr(1);
var target = document.getElementById(targetId);
// Try to support the name attribute
if(!target)
{
var nameTargets = document.getElementsByName(targetId);
// If nothing found, don't do anything
if(nameTargets.length == 0) return;
target = nameTargets[0];
}
// If the element does not have any parent, add the class to the <html> tag
lastParent = target.parentElement || document.documentElement;
lastParent.className += ' hastarget';
}, false);
var lastParent=null;
addEventListener('hashchange',function(){
//从上一个目标父级删除类
如果(最后一个父项)
{
lastParent.className=(“”+lastParent.className+“”)。替换('hastarget',“”);
lastParent=null;
}
//从位置散列中删除“#”
var targetId=document.location.hash.substr(1);
var target=document.getElementById(targetId);
//尝试支持name属性
如果(!目标)
{
var nameTargets=document.getElementsByName(targetId);
//如果什么也没找到,什么都不要做
if(nameTargets.length==0)返回;
target=nameTargets[0];
}
//如果元素没有任何父元素,则将该类添加到标记中
lastParent=target.parentElement | | document.documentElement;
lastParent.className+='hastarget';
},假);
使用angular,在控制器中或使用$rootScope
为整个应用程序公开哈希:
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()中缺少的#
。在HTML5中,您应该使用id
属性,而不是name
。感谢您的回答,这对我很有效,只需稍加修改。我将一个div和我的函数放入控制器$scope.currentHash=function(){return$location.hash;}代码>与相应的css.highlightDiv{边框:2px纯蓝色;}
<div data-ng-class="{'active': currentHash() == 'iid_7923'}">