在CSS中使用1个网址设置图片精灵

时间:2018-12-13 20:09:54

标签: css image sprite css-sprites

我想做的是在CSS中仅使用1个图片网址。

因此,只要更改图片或其他内容,我只需在CSS中更改1个url,而不是全部更改。

该代码已在使用图像精灵。 我只希望它在其中使用1个图片网址,而不是6个。

这将如何完成?

这是所有图像网址和背景位置所在的位置:

https://jsfiddle.net/g6oaht8f/286/

const searchQuery = "ben";
const pattern = [];

const exercises = [
  {
    name: "bench press",
    movement: ["push", "pull", "squat", "hinge"]
  },
  {
    name: "squat",
    movement: ["push", "pull", "squat", "hinge"]
  },
  {
    name: "squat",
    movement: ["squat", "hinge"]
  },
  {
    name: "pushup",
    movement: ["push", "pull", "squat", "hinge"]
  },
  {
    name: "pullup",
    movement: ["pull", "squat", "hinge"]
  },
  {
    name: "bent over row",
    movement: ["push", "pull", "hinge"]
  }
];

let filteredExercises = [];

if (searchQuery && pattern) {
  filteredExercises = exercises.filter(
    exercise =>
      exercise.name.toLowerCase().indexOf(searchQuery) !== -1 &&
      exercise.movement.some(movement =>
        pattern.some(pattern => pattern == movement)
      )
  );
} else if (pattern.length > 0) {
  filteredExercises = exercises.filter(exercise =>
    exercise.movement.some(movement =>
      pattern.some(pattern => pattern == movement)
    )
  );
} else if (searchQuery) {
  filteredExercises = exercises.filter(
    exercise => exercise.name.toLowerCase().indexOf(searchQuery) !== -1
  );
  console.log(filteredExercises);
}

console.log(filteredExercises);

2 个答案:

答案 0 :(得分:1)

在此提琴中查看CSS:https://jsfiddle.net/ksp4qoej/

请注意最相关的更改:

.jacketb,
.jacketc,
.jacketd,
.wrapb,
.wrapb::before,
.wrapd .img
.wrape,
.wraph,
.wrapf {
  background-image: url("https://i.imgur.com/Y0CrMX2.png");
  background-repeat: no-repeat;
}

我们在这里所做的是使用一个规则将图像作为背景应用于多类元素。需要更细致地更新背景位置值,这可以在文件中其他位置的单个选择器块中完成。

当您准备就绪时,使用SASS或LESS之类的内容来生成CSS可以为图像地图提供更简洁的代码。一探究竟! http://thesassway.com/intermediate/spriting-with-sass-and-compass

答案 1 :(得分:0)

David M的解决方案是正确的。我能看到的唯一问题是.wrapd .img之后缺少逗号(见下文)

.jacketb,
.jacketc,
.jacketd,
.wrapb,
.wrapb::before,
.wrapd .img,
.wrape,
.wraph,
.wrapf {
    background-image: url("https://i.imgur.com/Y0CrMX2.png");
    background-repeat: no-repeat;
}