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

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

when click the menu change the ::after background

问题

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

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

this is my html code:

<div class="menu">
  <div class="row" style="justify-content: center;">
       <div class="menu-item">
          <a href="" class="row" id="border" onclick="change(0)">
              <span>home</span>
            

          </a>
       </div>

       <div class="menu-item">
          <a href="" class="row" id="border" onclick="change(1)">
              <span>subjects <i class="fa-solid fa-angle-down"></i> </span>
             
          </a>
       </div>

       <div class="menu-item">
          <a href="" class="row" id="border"  onclick="change(2)">
              <span>expert solutions</span>
  
          </a>
       </div>
   </div>
</div>

and this is my css code:

:root
{
    --background-border-menu: red;
}
.menu
{
    width: 328px;
    background-color: blue;
}
.menu-item
{
    height: 70px;
    background-color: blanchedalmond;
    margin:0 5px;
}
.menu-item a
{
    position: relative;
    height: 70px;
    padding: 5px;
    font-size: 0.875rem;
    text-transform: capitalize;
    color: #2e3856;
    font-family: 'Pathway Extreme', sans-serif;
    font-weight: 600;
}

.menu-item a::after
{ 
    position: absolute;
    content: " ";
    width: 100%;
    height: 0.3rem;
    background-color: var(--background-border-menu);
    bottom: 0;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    left: 0;
}

and this is my js code:

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

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 中定义的变量,就像这样。这 消除了在处理程序中使用循环的需要。这里有一个最小可复制的示例

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

<!-- language: lang-js -->
document.addEventListener(`click`, handle);
const rootRule = getRootRule();
let defaultColor = "red";

createSomeDivs();

function handle(evt) {
  if (evt.target.classList.contains(`testColor`)) {
    defaultColor = defaultColor === `red` ? `green` : `red`;
    rootRule.setProperty(`--test-color`, defaultColor);
  }
}

function createSomeDivs() {
  const divs = [...Array(10)].map((_, i) => {
    const isEven = i % 2 == 0;
    return `<div class="${isEven ? `testColor` : `none`}">
      ${isEven ? ` ` : `I'm just a div`}
     </div>`;
  });
  document.body.insertAdjacentHTML(`beforeend`, divs.join(``))
}

function getRootRule() {
  return [...document.styleSheets[0].rules]
    .find(rule => 
      rule.cssText.trim().startsWith(`:root`))?.style;
}

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

:root {
  --test-color: red;
}

.testColor:after {
  content: "click me!";
  color: var(--test-color);
  cursor: pointer;
}

<!-- end snippet -->

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

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

<!-- language: lang-js -->
const cssEditFactory = window.LifeStyleFactory;
delete window.LifeStyleFactory;
const modifyCss = cssEditFactory({createWithId: `myCustomStylesheet`});
let currentColor = `green`;

// 添加一个处理程序(事件委托)
document.addEventListener(`click`, handle);

setStyleAndCreateDivs(currentColor);

function handle(evt) {
  if (evt.target.classList.contains(`testColorChanger`)) {
    let current = currentColor;
    // 切换颜色
    currentColor = current === `green` ? `blue` : `green`;

    // 重写CSS规则
    modifyCss(`:root { --my-color: ${currentColor}; }`);

    // 报告当前规则的文本
    console.clear();
    console.log(document.querySelector(`#myCustomStylesheet`)
      .sheet.rules[0].cssText);
  }
}

function setStyleAndCreateDivs(currentColor) {
  // 创建2个规则
  [`:root { 
      --my-color: ${currentColor}; 
      --test-hover-color: orange; }`,
   `.testColorChanger::after { 
      color: var(--my-color);
      content: ' I am div.testColorChanger::after. Click me! \0C';
      box-shadow: 1px 2px 5px #ccc;
      border-radius: 4px;
      margin: 0.8rem 0;
      cursor: pointer;
    }`,
    `.testColorChanger:hover:after {
      color: var(--test-hover-color);
    }`,
    `div:hover {
      color: red;
    }`]
  .forEach(rule => modifyCss(rule));  
  
  // 创建一些带有class testColorChanger的div
  const divs = [...Array(10)].map((_, i) => {
    const isEven = i % 2 == 0;
    return `<div class="${isEven ? `testColorChanger` : `none`}">
      ${isEven ? ` ` : `I'm just a div`}
     </div>`;
  });
  document.body.insertAdjacentHTML(`beforeend`, divs.join(``));
}

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

<script src="https://kooiinc.github.io/LifeCSS/index.browser.js"></script>

<!-- 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 -->

document.addEventListener(`click`, handle);
const rootRule = getRootRule();
let defaultColor = &quot;red&quot;;

createSomeDivs();

function handle(evt) {
  if (evt.target.classList.contains(`testColor`)) {
    defaultColor = defaultColor === `red` ? `green` : `red`;
    rootRule.setProperty(`--test-color`, defaultColor);
  }
}

function createSomeDivs() {
  const divs = [...Array(10)].map( (_, i) =&gt; {
    const isEven = i % 2 == 0;
    return `&lt;div class=&quot;${isEven ? `testColor` : `none`}&quot;&gt;
      ${isEven ? ` ` : `I&#39;m just a div`}
     &lt;/div&gt;`;
     });
  document.body.insertAdjacentHTML(`beforeend`, divs.join(``))
}

function getRootRule() {
  return [...document.styleSheets[0].rules]
    .find(rule =&gt; 
      rule.cssText.trim().startsWith(`:root`))?.style;
}

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

:root {
  --test-color: red;
}

.testColor:after {
  content: &quot;click me!&quot;;
  color: var(--test-color);
  cursor: pointer;
}

<!-- 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 -->

const cssEditFactory = window.LifeStyleFactory;
delete window.LifeStyleFactory;
const modifyCss = cssEditFactory({createWithId: `myCustomStylesheet`});
let currentColor = `green`;

// add a handler (event delegation)
document.addEventListener(`click`, handle);

setStyleAndCreateDivs(currentColor);

function handle(evt) {
  if (evt.target.classList.contains(`testColorChanger`)) {
    let current = currentColor;
    // toggle color
    currentColor = current === `green` ? `blue` : `green`;

    // rewrite the css rule
    modifyCss(`:root { --my-color: ${currentColor}; }`);

    // report the text of the current rule
    console.clear();
    console.log(document.querySelector(`#myCustomStylesheet`)
      .sheet.rules[0].cssText);
  }
}

function setStyleAndCreateDivs(currentColor) {
  // create 2 rules
  // \F60A
  [`:root { 
      --my-color: ${currentColor}; 
      --test-hover-color: orange; }`,
   `.testColorChanger::after { 
      color: var(--my-color);
      content: &#39; I am div.testColorChanger::after. Click me! \0C&#39;;
      box-shadow: 1px 2px 5px #ccc;
      border-radius: 4px;
      margin: 0.8rem 0;
      cursor: pointer;
    }`,
    `.testColorChanger:hover:after {
      color: var(--test-hover-color);
    }`,
    `div:hover {
      color: red;
    }`]
  .forEach(rule =&gt; modifyCss(rule));  
  
  // create some divs with class testColorChanger
  const divs = [...Array(10)].map( (_, i) =&gt; {
    const isEven = i % 2 == 0;
    return `&lt;div class=&quot;${isEven ? `testColorChanger` : `none`}&quot;&gt;
      ${isEven ? ` ` : `I&#39;m just a div`}
     &lt;/div&gt;`;
     });
  document.body.insertAdjacentHTML(`beforeend`, divs.join(``));
}

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

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

<!-- end snippet -->

答案2

得分: 0

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

<div class="menu">
  <div class="row" style="justify-content: center;">
    <div class="menu-item">
      <a href="" class="row" id="border" onclick="changeColor(this, 0)">
        <span>home</span>
      </a>
    </div>

    <div class="menu-item">
      <a href="" class="row" id="border" onclick="changeColor(this, 1)">
        <span>subjects <i class="fa-solid fa-angle-down"></i> </span>
      </a>
    </div>

    <div class="menu-item">
      <a href="" class="row" id="border" onclick="changeColor(this, 2)">
        <span>expert solutions</span>
      </a>
    </div>
  </div>
</div>
.menu-item a.clicked::after {
  content: "";
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: red; /* 将此处更改为所需的颜色 */
}
function changeColor(element, index) {
  // 从所有链接中删除'clicked'类
  const links = document.querySelectorAll('.menu-item a');
  links.forEach((link) => link.classList.remove('clicked'));

  // 将'clicked'类添加到单击的链接
  element.classList.add('clicked');
}
英文:

Here is a simple way to do it:

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

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

&lt;div class=&quot;menu&quot;&gt;
  &lt;div class=&quot;row&quot; style=&quot;justify-content: center;&quot;&gt;
    &lt;div class=&quot;menu-item&quot;&gt;
      &lt;a href=&quot;&quot; class=&quot;row&quot; id=&quot;border&quot; onclick=&quot;changeColor(this, 0)&quot;&gt;
        &lt;span&gt;home&lt;/span&gt;
      &lt;/a&gt;
    &lt;/div&gt;

    &lt;div class=&quot;menu-item&quot;&gt;
      &lt;a href=&quot;&quot; class=&quot;row&quot; id=&quot;border&quot; onclick=&quot;changeColor(this, 1)&quot;&gt;
        &lt;span&gt;subjects &lt;i class=&quot;fa-solid fa-angle-down&quot;&gt;&lt;/i&gt; &lt;/span&gt;
      &lt;/a&gt;
    &lt;/div&gt;

    &lt;div class=&quot;menu-item&quot;&gt;
      &lt;a href=&quot;&quot; class=&quot;row&quot; id=&quot;border&quot; onclick=&quot;changeColor(this, 2)&quot;&gt;
        &lt;span&gt;expert solutions&lt;/span&gt;
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

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

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

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

function changeColor(element, index) {
  // Remove the &#39;clicked&#39; class from all links
  const links = document.querySelectorAll(&#39;.menu-item a&#39;);
  links.forEach((link) =&gt; link.classList.remove(&#39;clicked&#39;));

  // Add the &#39;clicked&#39; class to the clicked link
  element.classList.add(&#39;clicked&#39;);
}

<!-- 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;
}

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

答案4

得分: -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");
}
});
}


<details>
<summary>英文:</summary>

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");
}
});
}


</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:

确定