握把框的 CSS 背景图案

Luk*_*uke 2 html css background-image

我想使用 CSS 创建一个“抓握”背景,用于指示元素是可拖动的。(参见https://ux.stackexchange.com/a/34639/39138

目前我有一个dnd该项目的类,CSS 如下所示:

.dnd {
  background: #99bbee; /* would like to be able to change this dynamically */
  padding: 1em;
  margin: 2em;
  border-radius: 0.25em;
  width: 14em;
  transition: all 0.25s;
}
.dnd:hover {
  box-shadow: 0.25em 0.25em 0.3em rgba(0,0,0,0.2);
  margin: 1.75em 2.1em 2.25em 1.9em;
  cursor: move; /* fallback if grab cursor is unsupported */
  cursor: grab;
  cursor: -moz-grab;
  cursor: -webkit-grab;
}
.dnd:active { 
  cursor: grabbing;
  cursor: -moz-grabbing;
  cursor: -webkit-grabbing;
}
.dnd::before { /* the grip */
  content: " ";
  display: inline-block;
  width: 1.5em;
  height: 2em;
  margin: -0.5em 0.75em -0.5em -0.5em; 

  background-color: transparent;
  background-size: 0.5em 0.5em;
  background-position: 0 0;
  /* Background image - unfortunately requires background color */
  background-image: 
    -webkit-linear-gradient(#99bbee 50%, transparent 50%),
    -webkit-linear-gradient(left, rgba(0,0,0,0.2) 50%, transparent 50%);
  background-image: 
    -moz-linear-gradient(#99bbee 50%, transparent 50%),
    -moz-linear-gradient(left, rgba(0,0,0,0.2) 50%, transparent 50%);
  background-image: 
    -o-linear-gradient(#99bbee 50%, transparent 50%),
    -o-linear-gradient(left, rgba(0,0,0,0.2) 50%, transparent 50%);
  background-image: 
    linear-gradient(#99bbee 50%, transparent 50%),
    linear-gradient(to right, rgba(0,0,0,0.2) 50%, transparent 50%);
}
Run Code Online (Sandbox Code Playgroud)

...这可以创建一些盒子作为手柄上的背景,但我不希望手柄伪元素依赖于硬编码的背景颜色(在这种情况下#99bbee;它使用它是可以的rgba(0,0,0,0.2))。有没有办法重写这个 CSS 背景图像,使其在背景颜色方面更加灵活?

这是一个jsfiddle: https: //jsfiddle.net/luken/r69wfwjd/5/


2021 编辑: CSS 变量现在得到广泛支持,因此它们可能是最好的解决方案。

Ric*_*ler 5

我认为最好的选择可能是 SVG 图像背景。

.grippie事实上,如果你在写答案时看一下stackoverflow自己的grip来扩展textarea( ),它使用的是SVG背景

因此,我们的想法是使用 cssbackground属性url(...)数据 uri作为 url。

SVG 代码取自此处

.grip {
  background-size: cover;
  background: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1IiBoZWlnaHQ9IjUiPgo8cmVjdCB3aWR0aD0iMSIgaGVpZ2h0PSIxIiBmaWxsPSIjODg4Ij48L3JlY3Q+Cjwvc3ZnPg==");
  width: 10px;
  height: 15px;
  cursor: grab;
  cursor: -webkit-grab;
  margin: 0.5em;
}

.container {
  display: flex;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container" draggable="true">
  <div class="grip"></div>
  <div class="content">A thing with a grip</div>
</div>
<div class="container" draggable="true">
  <div class="grip"></div>
  <div class="content">A thing with a grip</div>
</div>
Run Code Online (Sandbox Code Playgroud)