내 탐색 메뉴에 4 개의 항목이 있습니다.
<nav>
<ul >
<li><a href="/a.html">ITEM A</a></li>
<li><a href="/b.html">ITEM B</a></li>
<li><a href="/c.html">ITEM C</a></li>
</ul>
</nav>
이러한 항목을 가리 키거나 클릭하면 색상이 변경됩니다. 그러나 페이지 새로 고침 후 색상이 사라집니다. 사용자가를 클릭 b.html
하면 페이지가 다시로드 될 때 메뉴 항목 B의 색상이 달라지기를 원합니다.
내 질문을 명확히하고 있습니까?
감사.
내가 생각할 수있는 가장 간단한 jQuery 기반 대답은 href
속성 값 을 검색 하고 현재 페이지의 URL이 해당 속성 값으로 끝나는 지 테스트하는 것입니다.
// getting the current location:
var url = document.location.href;
// iterating over each <a> element using filter(), using a
// more specific selector will reduce the work undertaken:
$('a').filter(function(i, a) {
// i: the index of the current <a> element within the
// jQuery collection;
// a: the current <a> DOM node.
// String.prototype.endsWith() returns a Boolean, true
// if the supplied string (url) ends with the supplied
// argument (the attribute-value of the 'href'
// attribute of the current <a> element):
return url.endsWith( a.getAttribute('href') );
// we add the 'activeClass' class-name to those elements
// retained in the collection, to provide a styling hook:
}).addClass('activeClass');
또는 브라우저가 지원하지 않는 (다소 가능성이있는) 이벤트 String.prototype.endsWith()
:
var url = document.location.href;
$('a').filter(function(i, a) {
// retaining only those <a> elements whose
// 'href' property (the absolute URL
// derived from the <a> elements' href
// attribute) is equal to the document location:
return url == a.href;
}).addClass('activeClass');
또는 일반 JavaScript에서 :
var aElements = Array.from(document.querySelectorAll('a')),
// or, in the event that ES6 Array.from() is unavailable:
// var aElements = Array.prototype.slice.call(document.querySelectorAll('a'), 0),
url = document.location.href;
aElements.filter(Function (currentAnchor) {
return currentAnchor.href == url;
}).forEach(function (currentAnchor) {
currentAnchor.classList.add('activeClass');
});
분명히 위의 모든 접근 방식에서는 찾은 링크의 스타일을 지정하기 위해 CSS에 클래스를 정의해야합니다. 예를 들면 다음과 같습니다.
a:active,
a.activeClass {
color: #f90;
text-decoration: underline;
}
다소 낙관적이기는하지만 미래의 어느 시점에서의 의사 클래스 는 현재 페이지를 가리키는 요소의 :local-link
스타일 을 지정할 수 있습니다 <a>
. 예를 들면 다음과 같습니다.
a:active,
a:local-link {
color: #f90;
text-decoration: underline;
}
나는이 점에 유의하겠습니다 만, 글을 쓰는 시점에서,이 아직 구현되지 않으며, 심지어 나열 에 caniuse.com .
참고 문헌 :
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다