【发布时间】:2017-03-03 00:41:10
【问题描述】:
示例使用(我想要的)
div::after {
content: var(--mouse-x) ' / ' var(--mouse-y);
}
测试用例显示它不起作用:
CodePen: CSS Variables in Pseudo Element's "content:" Property (a test case) by Jase Smith
document.addEventListener('mousemove', (e) => {
document.documentElement.style.setProperty('--mouse-x', e.clientX)
document.documentElement.style.setProperty('--mouse-y', e.clientY)
// output for explanation text
document.querySelector('.x').innerHTML = e.clientX
document.querySelector('.y').innerHTML = e.clientY
})
/* what I want!! */
div::after {
content: var(--mouse-x, 245)" / " var(--mouse-y, 327);
}
/* setup and presentation styles */
div::before {
content: 'mouse position:';
}
div {
position: absolute;
top: 0;
left: 0;
transform: translate(calc(var(--mouse-x, 245) * 1px), calc(var(--mouse-y, 327) * 1px));
width: 10em;
height: 10em;
background: #ff3b80;
color: #fff;
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
border-radius: 100%;
will-change: transform;
}
body {
margin: 2em;
font-family: sans-serif;
}
p {
max-width: 50%;
min-width: 25em;
}
<!-- test case: element with pseudo element -->
<div></div>
<!-- explanation (not test case) -->
<main>
<pre><code>div::after {
content: var(--mouse-x) ' / ' var(--mouse-y);
}</code></pre>
<h1>If this worked...</h1>
<p>
We should see something like this: <b><span class="x">245</span> / <span class="y">327</span></b> updating with the mousemove coordinates inside the pseudo <i>::after</i> element for the div.
</p>
</main>
【问题讨论】:
-
我建议直接在问题中发布代码,以防将来链接中断。
-
啊,谢谢你的提示。我希望它只是嵌入并显示 CodePen 演示......
-
这是 stackoverflow.com/questions/38751778/… 的副本,但由于您在这里处理数字,所以 darrylyeo 的 hack 就可以了。
标签: css pseudo-element css-variables