在:: before伪类中更改'content'属性

时间:2018-06-22 15:09:50

标签: javascript css pseudo-class

JSFiddle

在我的JS中,我试图访问dislpay_object :: before类的'content'属性。 我需要将“内容”(文本)设置为div在页面上的位置。

我已经进行了无数次搜索,但是在这些类型的伪类上却没有找到任何深入的东西。

  .display_object {
  position: absolute;
  border: thin solid black;
  width: 15cm;
  white-space: nowrap;
}

.display_object:active::before {
  content: "x,y";
  /*needs to be changed to actual values*/
  display: block;
  position: absolute;
  background: rgba(0, 0, 0, 0.48);
  padding: 1em 3em;
  color: white;
  font-size: .8em;
  bottom: 1.6em;
  left: -1px;
  white-space: nowrap;
}

如何通过JS引用:active ::的.content并将其设置为当前位置?

1 个答案:

答案 0 :(得分:1)

通过this answer,您可以使用beforecontent伪元素的attr()属性设置为父div的属性:

content: attr(data-before);

然后只需在事件处理程序中更新该属性即可:

div.setAttribute('data-before',`x: ${mousePosition.x}, y: ${mousePosition.y}`);

工作片段:

		var mousePosition;
		var offset = [0, 0];
		var div;
		var isDown = false;

		div = document.createElement("div");

		div.className = "display_object";
		div.innerHTML = "Draggable box:  ";

		document.body.appendChild(div);

		div.addEventListener('mousedown', function(e) {
		  isDown = true;
		  offset = [
		    div.offsetLeft - e.clientX,
		    div.offsetTop - e.clientY
		  ];
		}, true);

		document.addEventListener('mouseup', function() {
		  isDown = false;
		}, true);

		document.addEventListener('mousemove', function(event) {
		event.preventDefault();
		if (isDown) {

		  mousePosition = {

		    x: event.clientX,
		    y: event.clientY

		  };

		  div.style.left = (mousePosition.x + offset[0]) + 'px';
		  div.style.top = (mousePosition.y + offset[1]) + 'px';

			div.setAttribute('data-before',`x: ${mousePosition.x}, y: ${mousePosition.y}`);

		}
		}, true)
		;
.display_object {
  position: absolute;
  border: thin solid black;
  width: 15cm;
  white-space: nowrap;
}

.display_object:active::before {
  content: attr(data-before);
  display: block;
  position: absolute;
  background: rgba(0, 0, 0, 0.48);
  padding: 1em 3em;
  color: white;
  font-size: .8em;
  bottom: 1.6em;
  left: -1px;
  white-space: nowrap;
}