HTML/CSS/Javascript:使用 javascript 更改 ul-li:before backround-image

问题描述 投票:0回答:2

我有一个 div,其中包含一个 ul,其中有一个自定义图像作为标记:

HTML:

    <div class="block">
      <h2>Custom List</h2>
      <div class="ul-custom">
        <ul>
          <li>...</li>
          <li>..</li>
          <li>...</li>
      </ul>
      </div>
    </div>

CSS:

.ul-custom {
  ul {
    list-style: none;
    padding-left: 0;
    margin: 0;

    li {
      position: relative;
      padding-left: 20px;

      &:before {
        content: "";
        width: 15px;
        height: 26px;
        position: absolute;
        background-image: url("li-red.png");
        background-size: contain;
        background-position: center;
        background-repeat: no-repeat;
        left: 0;
        top: 0;
      }
    }
  }
}

我现在的问题是,由于我在 li:before 中有图像,有没有办法更改 javascript 中的 url?

我已经搜索过但找不到任何内容,但我确信互联网上已经有关于此的内容。

希望有人可以帮助我,提前谢谢!


或者是否有一种“更简单”或“更好”的方法将自定义图像放在 li 上,以便可以通过 javascript 进行更改?

javascript html css html-lists
2个回答
0
投票

如果我理解正确的话,你想使用javascript替换背景图像(“li-red.png”)。你应该能够这样做:

// Select the li elements
const liElements = document.querySelectorAll('.ul-custom li');

// Function to change the background image
function changeBackgroundImage(element, newImageUrl) {
  element.style.backgroundImage = `url("${newImageUrl}")`;
}

// Example usage: Change the background image of the first li element
// Use this function where you want it to be called
changeBackgroundImage(liElements[0], 'new-image.png');

0
投票

感谢@CBroe,解决方案非常简单。

HTML-代码如上:

   <div class="block">
      <h2>Custom List</h2>
      <div class="ul-custom">
        <ul>
          <li>...</li>
          <li>..</li>
          <li>...</li>
      </ul>
      </div>
    </div>

CSS(新):

.ul-custom ul {
  list-style: none;
  padding-left: 0;
  margin: 0;
}

.ul-custom ul li {
  position: relative;
  padding-left: 20px;
}

.ul-custom ul li:before {
  content: "";
  width: 15px;
  height: 15px;
  position: absolute;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  left: 0;
  top: 0;
}

.ul-custom.marker-1 ul li:before {
  background-image: url("...");
}
.ul-custom.marker-2 ul li:before {
  background-image: url("...");
}
.ul-custom.marker-3 ul li:before {
  background-image: url("...");
}
.ul-custom.marker-4 ul li:before {
  background-image: url("...");
}

Javascript:

let ul = document.querySelectorAll(".ul-custom");

ul.forEach((list) => {
  switch (...) {
    case "...":
      list.classList.add("marker-2");
      break;
    case "...":
      list.classList.add("marker-3");
      break;
    case "...":
      list.classList.add("marker-4");
      break;
    default:
      list.classList.add("marker-1");
      break;
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.