点击菜单时更改 ::after 背景

huangapple go评论106阅读模式
英文:

when click the menu change the ::after background

问题

  1. .menu-item a::after
  2. {
  3. /* ... */
  4. background-color: var(--background-border-menu);
  5. /* ... */
  6. }
  1. function change(i)
  2. {
  3. var item = document.querySelectorAll("#border");
  4. item[i].style.setProperty("--background-border-menu" , "blue");
  5. }
英文:

how can i change the color of ::after pseudo-element when i click the a tag?

this is my html code:

  1. <div class="menu">
  2. <div class="row" style="justify-content: center;">
  3. <div class="menu-item">
  4. <a href="" class="row" id="border" onclick="change(0)">
  5. <span>home</span>
  6. </a>
  7. </div>
  8. <div class="menu-item">
  9. <a href="" class="row" id="border" onclick="change(1)">
  10. <span>subjects <i class="fa-solid fa-angle-down"></i> </span>
  11. </a>
  12. </div>
  13. <div class="menu-item">
  14. <a href="" class="row" id="border" onclick="change(2)">
  15. <span>expert solutions</span>
  16. </a>
  17. </div>
  18. </div>
  19. </div>

and this is my css code:

  1. :root
  2. {
  3. --background-border-menu: red;
  4. }
  5. .menu
  6. {
  7. width: 328px;
  8. background-color: blue;
  9. }
  10. .menu-item
  11. {
  12. height: 70px;
  13. background-color: blanchedalmond;
  14. margin:0 5px;
  15. }
  16. .menu-item a
  17. {
  18. position: relative;
  19. height: 70px;
  20. padding: 5px;
  21. font-size: 0.875rem;
  22. text-transform: capitalize;
  23. color: #2e3856;
  24. font-family: 'Pathway Extreme', sans-serif;
  25. font-weight: 600;
  26. }
  27. .menu-item a::after
  28. {
  29. position: absolute;
  30. content: " ";
  31. width: 100%;
  32. height: 0.3rem;
  33. background-color: var(--background-border-menu);
  34. bottom: 0;
  35. border-top-left-radius: 5px;
  36. border-top-right-radius: 5px;
  37. left: 0;
  38. }

and this is my js code:

  1. function change(i)
  2. {
  3. var item = document.querySelectorAll("#border");
  4. item[i].style.setProperty("--background-border-menu" , "blue");
  5. }

I want when I click on one of my items, only that item's change the a::after background color
When I click, it changes, but I don't know how to remove the previous item

答案1

得分: 1

编辑一个在 :root 中定义的变量,就像这样。这 消除了在处理程序中使用循环的需要。这里有一个最小可复制的示例

  1. <!-- begin snippet: js hide: false console: true babel: false -->
  2. <!-- language: lang-js -->
  3. document.addEventListener(`click`, handle);
  4. const rootRule = getRootRule();
  5. let defaultColor = "red";
  6. createSomeDivs();
  7. function handle(evt) {
  8. if (evt.target.classList.contains(`testColor`)) {
  9. defaultColor = defaultColor === `red` ? `green` : `red`;
  10. rootRule.setProperty(`--test-color`, defaultColor);
  11. }
  12. }
  13. function createSomeDivs() {
  14. const divs = [...Array(10)].map((_, i) => {
  15. const isEven = i % 2 == 0;
  16. return `<div class="${isEven ? `testColor` : `none`}">
  17. ${isEven ? ` ` : `I'm just a div`}
  18. </div>`;
  19. });
  20. document.body.insertAdjacentHTML(`beforeend`, divs.join(``))
  21. }
  22. function getRootRule() {
  23. return [...document.styleSheets[0].rules]
  24. .find(rule =>
  25. rule.cssText.trim().startsWith(`:root`))?.style;
  26. }
  27. <!-- language: lang-css -->
  28. :root {
  29. --test-color: red;
  30. }
  31. .testColor:after {
  32. content: "click me!";
  33. color: var(--test-color);
  34. cursor: pointer;
  35. }
  36. <!-- end snippet -->

或者使用这个小型库我写的。它可以创建/修改/删除CSS规则。以下是如何使用它来切换CSS变量(来自 :root)的示例。

  1. <!-- begin snippet: js hide: true console: true babel: false -->
  2. <!-- language: lang-js -->
  3. const cssEditFactory = window.LifeStyleFactory;
  4. delete window.LifeStyleFactory;
  5. const modifyCss = cssEditFactory({createWithId: `myCustomStylesheet`});
  6. let currentColor = `green`;
  7. // 添加一个处理程序(事件委托)
  8. document.addEventListener(`click`, handle);
  9. setStyleAndCreateDivs(currentColor);
  10. function handle(evt) {
  11. if (evt.target.classList.contains(`testColorChanger`)) {
  12. let current = currentColor;
  13. // 切换颜色
  14. currentColor = current === `green` ? `blue` : `green`;
  15. // 重写CSS规则
  16. modifyCss(`:root { --my-color: ${currentColor}; }`);
  17. // 报告当前规则的文本
  18. console.clear();
  19. console.log(document.querySelector(`#myCustomStylesheet`)
  20. .sheet.rules[0].cssText);
  21. }
  22. }
  23. function setStyleAndCreateDivs(currentColor) {
  24. // 创建2个规则
  25. [`:root {
  26. --my-color: ${currentColor};
  27. --test-hover-color: orange; }`,
  28. `.testColorChanger::after {
  29. color: var(--my-color);
  30. content: ' I am div.testColorChanger::after. Click me! \0C';
  31. box-shadow: 1px 2px 5px #ccc;
  32. border-radius: 4px;
  33. margin: 0.8rem 0;
  34. cursor: pointer;
  35. }`,
  36. `.testColorChanger:hover:after {
  37. color: var(--test-hover-color);
  38. }`,
  39. `div:hover {
  40. color: red;
  41. }`]
  42. .forEach(rule => modifyCss(rule));
  43. // 创建一些带有class testColorChanger的div
  44. const divs = [...Array(10)].map((_, i) => {
  45. const isEven = i % 2 == 0;
  46. return `<div class="${isEven ? `testColorChanger` : `none`}">
  47. ${isEven ? ` ` : `I'm just a div`}
  48. </div>`;
  49. });
  50. document.body.insertAdjacentHTML(`beforeend`, divs.join(``));
  51. }
  52. <!-- language: lang-html -->
  53. <script src="https://kooiinc.github.io/LifeCSS/index.browser.js"></script>
  54. <!-- end snippet -->
英文:

Edit a variable defined in :root like this. It nullifies the need for a loop in the handler. Here's a minimal reproducable example.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. document.addEventListener(`click`, handle);
  2. const rootRule = getRootRule();
  3. let defaultColor = &quot;red&quot;;
  4. createSomeDivs();
  5. function handle(evt) {
  6. if (evt.target.classList.contains(`testColor`)) {
  7. defaultColor = defaultColor === `red` ? `green` : `red`;
  8. rootRule.setProperty(`--test-color`, defaultColor);
  9. }
  10. }
  11. function createSomeDivs() {
  12. const divs = [...Array(10)].map( (_, i) =&gt; {
  13. const isEven = i % 2 == 0;
  14. return `&lt;div class=&quot;${isEven ? `testColor` : `none`}&quot;&gt;
  15. ${isEven ? ` ` : `I&#39;m just a div`}
  16. &lt;/div&gt;`;
  17. });
  18. document.body.insertAdjacentHTML(`beforeend`, divs.join(``))
  19. }
  20. function getRootRule() {
  21. return [...document.styleSheets[0].rules]
  22. .find(rule =&gt;
  23. rule.cssText.trim().startsWith(`:root`))?.style;
  24. }

<!-- language: lang-css -->

  1. :root {
  2. --test-color: red;
  3. }
  4. .testColor:after {
  5. content: &quot;click me!&quot;;
  6. color: var(--test-color);
  7. cursor: pointer;
  8. }

<!-- end snippet -->

Or use this small library I've written. It enables creation/modification/removal of css rules. Here's an example of how to use it to toggle a css variable (from :root).

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

  1. const cssEditFactory = window.LifeStyleFactory;
  2. delete window.LifeStyleFactory;
  3. const modifyCss = cssEditFactory({createWithId: `myCustomStylesheet`});
  4. let currentColor = `green`;
  5. // add a handler (event delegation)
  6. document.addEventListener(`click`, handle);
  7. setStyleAndCreateDivs(currentColor);
  8. function handle(evt) {
  9. if (evt.target.classList.contains(`testColorChanger`)) {
  10. let current = currentColor;
  11. // toggle color
  12. currentColor = current === `green` ? `blue` : `green`;
  13. // rewrite the css rule
  14. modifyCss(`:root { --my-color: ${currentColor}; }`);
  15. // report the text of the current rule
  16. console.clear();
  17. console.log(document.querySelector(`#myCustomStylesheet`)
  18. .sheet.rules[0].cssText);
  19. }
  20. }
  21. function setStyleAndCreateDivs(currentColor) {
  22. // create 2 rules
  23. // \F60A
  24. [`:root {
  25. --my-color: ${currentColor};
  26. --test-hover-color: orange; }`,
  27. `.testColorChanger::after {
  28. color: var(--my-color);
  29. content: &#39; I am div.testColorChanger::after. Click me! \0C&#39;;
  30. box-shadow: 1px 2px 5px #ccc;
  31. border-radius: 4px;
  32. margin: 0.8rem 0;
  33. cursor: pointer;
  34. }`,
  35. `.testColorChanger:hover:after {
  36. color: var(--test-hover-color);
  37. }`,
  38. `div:hover {
  39. color: red;
  40. }`]
  41. .forEach(rule =&gt; modifyCss(rule));
  42. // create some divs with class testColorChanger
  43. const divs = [...Array(10)].map( (_, i) =&gt; {
  44. const isEven = i % 2 == 0;
  45. return `&lt;div class=&quot;${isEven ? `testColorChanger` : `none`}&quot;&gt;
  46. ${isEven ? ` ` : `I&#39;m just a div`}
  47. &lt;/div&gt;`;
  48. });
  49. document.body.insertAdjacentHTML(`beforeend`, divs.join(``));
  50. }

<!-- language: lang-html -->

  1. &lt;script src=&quot;https://kooiinc.github.io/LifeCSS/index.browser.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案2

得分: 0

这是一个简单的方法来实现它:

  1. <div class="menu">
  2. <div class="row" style="justify-content: center;">
  3. <div class="menu-item">
  4. <a href="" class="row" id="border" onclick="changeColor(this, 0)">
  5. <span>home</span>
  6. </a>
  7. </div>
  8. <div class="menu-item">
  9. <a href="" class="row" id="border" onclick="changeColor(this, 1)">
  10. <span>subjects <i class="fa-solid fa-angle-down"></i> </span>
  11. </a>
  12. </div>
  13. <div class="menu-item">
  14. <a href="" class="row" id="border" onclick="changeColor(this, 2)">
  15. <span>expert solutions</span>
  16. </a>
  17. </div>
  18. </div>
  19. </div>
  1. .menu-item a.clicked::after {
  2. content: "";
  3. display: inline-block;
  4. width: 10px;
  5. height: 10px;
  6. background-color: red; /* 将此处更改为所需的颜色 */
  7. }
  1. function changeColor(element, index) {
  2. // 从所有链接中删除'clicked'类
  3. const links = document.querySelectorAll('.menu-item a');
  4. links.forEach((link) => link.classList.remove('clicked'));
  5. // 将'clicked'类添加到单击的链接
  6. element.classList.add('clicked');
  7. }
英文:

Here is a simple way to do it:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

  1. &lt;div class=&quot;menu&quot;&gt;
  2. &lt;div class=&quot;row&quot; style=&quot;justify-content: center;&quot;&gt;
  3. &lt;div class=&quot;menu-item&quot;&gt;
  4. &lt;a href=&quot;&quot; class=&quot;row&quot; id=&quot;border&quot; onclick=&quot;changeColor(this, 0)&quot;&gt;
  5. &lt;span&gt;home&lt;/span&gt;
  6. &lt;/a&gt;
  7. &lt;/div&gt;
  8. &lt;div class=&quot;menu-item&quot;&gt;
  9. &lt;a href=&quot;&quot; class=&quot;row&quot; id=&quot;border&quot; onclick=&quot;changeColor(this, 1)&quot;&gt;
  10. &lt;span&gt;subjects &lt;i class=&quot;fa-solid fa-angle-down&quot;&gt;&lt;/i&gt; &lt;/span&gt;
  11. &lt;/a&gt;
  12. &lt;/div&gt;
  13. &lt;div class=&quot;menu-item&quot;&gt;
  14. &lt;a href=&quot;&quot; class=&quot;row&quot; id=&quot;border&quot; onclick=&quot;changeColor(this, 2)&quot;&gt;
  15. &lt;span&gt;expert solutions&lt;/span&gt;
  16. &lt;/a&gt;
  17. &lt;/div&gt;
  18. &lt;/div&gt;
  19. &lt;/div&gt;

<!-- language: lang-css -->

  1. .menu-item a.clicked::after {
  2. content: &quot;&quot;;
  3. display: inline-block;
  4. width: 10px;
  5. height: 10px;
  6. background-color: red; /* Change this to the desired color */
  7. }

<!-- language: lang-js -->

  1. function changeColor(element, index) {
  2. // Remove the &#39;clicked&#39; class from all links
  3. const links = document.querySelectorAll(&#39;.menu-item a&#39;);
  4. links.forEach((link) =&gt; link.classList.remove(&#39;clicked&#39;));
  5. // Add the &#39;clicked&#39; class to the clicked link
  6. element.classList.add(&#39;clicked&#39;);
  7. }

<!-- end snippet -->

答案3

得分: -1

let currentItem = null;
function change(i) {
const items = document.querySelectorAll("#border");
if (currentItem !== null) {
currentItem.style.setProperty("--background-border-menu", "red");
}
const clickedItem = items[i];
clickedItem.style.setProperty("--background-border-menu", "blue");
currentItem = clickedItem;
}

英文:
  1. let currentItem = null;
  2. function change(i) {
  3. const items = document.querySelectorAll(&quot;#border&quot;);
  4. if (currentItem !== null) {
  5. currentItem.style.setProperty(&quot;--background-border-menu&quot;, &quot;red&quot;);
  6. }
  7. const clickedItem = items[i];
  8. clickedItem.style.setProperty(&quot;--background-border-menu&quot;, &quot;blue&quot;);
  9. currentItem = clickedItem;
  10. }

答案4

得分: -1

  1. 这应该会起作用

function change(i) {
event.preventDefault();
var items = document.querySelectorAll(".menu-item a");
items.forEach(function(item, index) {
if (index === i) {
item.style.setProperty("--background-border-menu", "blue");
} else {
item.style.setProperty("--background-border-menu", "red");
}
});
}

  1. <details>
  2. <summary>英文:</summary>
  3. this should do the trick

function change(i) {
event.preventDefault();
var items = document.querySelectorAll(".menu-item a");
items.forEach(function(item, index) {
if (index === i) {
item.style.setProperty("--background-border-menu", "blue");
} else {
item.style.setProperty("--background-border-menu", "red");
}
});
}

  1. </details>

huangapple
  • 本文由 发表于 2023年7月3日 21:23:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定