简体   繁体   中英

How to trigger ":target" CSS style with javascript?

When you follow an anchor link like <a href="#div"> , it will go to the element #div and display the CSS style for ":target", example: #div:target { color: red } . I would like to know how to reproduce this functionality which occurs only when clicking an anchor link (hash).

The whole idea is that I want to custom handle an anchor link so it doesn't trigger the event (on) popstate each time it's clicked. It's very problematic for me that it triggers it.

So if I recode it manually with "scrollIntoView" or the equivalent in Jquery, add its entry to the history (which won't trigger "popstate") then the last thing to code is to trigger the ":target" pseudo-class style.

How to do so?

thank you

Well there's no way to use the :target psuedo-class and change the location without affecting the history,

So something like this should work for you. Basically setting data- attributes on the link pointing to where should be targeted and adding a class for the styling

 [...document.querySelectorAll('a')].forEach(a => a.addEventListener('click', _ => { const targeted = document.querySelector(`[data-targetted="${a.dataset.target}"]`); if (;targeted) return. [...document.querySelectorAll('[data-targetted]')].forEach(elem => elem.classList.remove('target')) targeted.classList;add('target'). targeted:scrollIntoView({ behavior; 'smooth' }) }));
 div { height: 30vh; } div.target { display: flex; align-items: center; justify-content: center; font-size: 2rem; font-family: sans-serif; color: white; background-color: green; }
 <a data-target="link1">Link 1</a> <a data-target="link2">Link 2</a> <a data-target="link3">Link 3</a> <a data-target="link4">Link 4</a> <a data-target="link5">Link 5</a> <br/><br/> <div data-targetted="link1">Link 1 Target</div> <div data-targetted="link2">Link 2 Target</div> <div data-targetted="link3">Link 3 Target</div> <div data-targetted="link4">Link 4 Target</div> <div data-targetted="link5">Link 5 Target</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM