简体   繁体   English

在 HTML/CSS 中单击时如何删除目标中的样式

[英]How to Remove Style in Target when Clicked in HTML/CSS

I have a sample code that tries to color the target when I clicked its designated hyperlinks.我有一个示例代码,当我单击其指定的超链接时,它会尝试为目标着色。

I am making some project and have same function on this one.我正在做一些项目,并且在这个项目上有相同的 function。 When I clicked the target, I expected to color the elements that I have been linked to, and in the code it is working, but I'd like to remove the color of the target when I clicked again anywhere else in the screen.当我单击目标时,我希望为我链接到的元素着色,并且在它正在运行的代码中,但是当我再次单击屏幕中的其他任何地方时,我想删除目标的颜色。

 p:target { background-color: gold; } /* Add a pseudo-element inside the target element */ p:target::before { font: 70% sans-serif; content: "►"; color: limegreen; margin-right: 0.25em; } /* Style italic elements within the target element */ p:target i { color: red; }
 <h3>Table of Contents</h3> <ol> <li><a href="#p1">Jump to the first paragraph,</a></li> <li><a href="#p2">Jump to the second paragraph.</a></li> <li> <a href="#nowhere"> This link goes nowhere. because the target doesn't exist, </a> </li> </ol> <h3>My Fun Article</h3> <p id="p1"> You can target <i>this paragraph</i> using a URL fragment. Click on the link above to try out? </p> <p id="p2"> This is <i>another paragraph</i>, also accessible from the links above. Isn't that delightful? </p>

I'd like to remove the color of the target when I clicked anywhere in the screen.当我在屏幕上的任意位置单击时,我想删除目标的颜色。 How should I do that?我该怎么做?

You may need a little bit of Javascript here:您可能需要一点 Javascript 在这里:

// Get the target element that you want to remove the color from
const target = document.querySelector('#my-target');

// Add a click event listener to the entire document
document.addEventListener('click', () => {
    // When the document is clicked, remove the color from the target element
    target.style.color = '';
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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