Dan*_*Dan 8 html javascript css css-selectors pseudo-element
我一直在寻找这个问题的答案,但未能找到有效的答案。我们以以下网站为例:https: //www.atlassian.com/devops
以下元素之前有一个伪元素:
var e = document.querySelector('li[class=language-selector]');
e.getClientRects();
top: 9797
bottom: 9818
left: 78
right: 162
x: 78
y: 9797
width: 85
height: 21
Run Code Online (Sandbox Code Playgroud)
函数 window.getCompulatedStyle 返回顶部、底部、左侧等的一些值:
window.getComputedStyle(e, ':before').top; //10.5
window.getComputedStyle(e, ':before').bottom; //-9.5
window.getComputedStyle(e, ':before').left; //-26
window.getComputedStyle(e, ':before').right; //90.6
window.getComputedStyle(e, ':before').x; //0
window.getComputedStyle(e, ':before').y; //0
window.getComputedStyle(e, ':before').width; //20
window.getComputedStyle(e, ':before').height; //20
Run Code Online (Sandbox Code Playgroud)
起初,它似乎是相对于基本元素的值,但如果我检查同一页面中的其他元素,行为似乎不一致:
var e3=document.querySelectorAll('blockquote[class="cite large-quote"]')[0];
top: 2303
bottom: 2408
left: 78
right: 1038
x: 78
y: 2303
width: 960
height: 105
Run Code Online (Sandbox Code Playgroud)
函数 window.getCompulatedStyle 返回以下内容:
window.getComputedStyle(e3, ':before').top; //-25
window.getComputedStyle(e3, ':before').bottom; //-50
window.getComputedStyle(e3, ':before').left; //0
window.getComputedStyle(e3, ':before').right; //889.25
window.getComputedStyle(e3, ':before').x; //0
window.getComputedStyle(e3, ':before').y; //0
window.getComputedStyle(e3, ':before').width; //70.75
window.getComputedStyle(e3, ':before').height; //180
Run Code Online (Sandbox Code Playgroud)
例如,第一个伪元素的顶部和底部分别为 10.5 和 -9.5,(10.5) - (-9.5) 是伪元素 (20) 的高度。
第二个伪元素的顶部和底部分别为 -25 和 -50,但伪元素的高度为 180。它们的“position”属性都具有“absolute”。所以行为是不一致的。
如果有人能够阐明如何获取伪元素的位置或坐标,我们将不胜感激。
css 属性bottom与边界矩形的属性不同bottom。事实上,在第一个测试中,顶部和底部 css 值最终成为伪元素的高度只是巧合。
边界矩形bottom是根据其 y 位置和高度计算的:
https://drafts.fxtf.org/geometry/#dom-domrectreadonly-domrect-bottom
获取底部属性时,必须返回 max(y 坐标,y 坐标 + 高度尺寸)。
然而cssbottom属性是一个位置值。使用absolute定位元素:
https://www.w3.org/TR/CSS2/visuren.html#propdef-bottom
与“top”类似,但指定框的下边距边缘在框包含块的底部之上偏移多远。
所以不能简单地使用公式bottom-top来获取伪元素的高度。您必须考虑最近定位的容器元素的高度,在您的情况下是块引用。
因此对于 blockquote 元素:它的高度是105px。报价的顶部25px高于顶部,底部50px低于底部。通过这些值,您可以获得伪元素的高度:
105 - -25 - -50 = 180
Run Code Online (Sandbox Code Playgroud)
至于坐标:x,y 属性似乎是特定于浏览器的,因为它们在 Firefox、IE 等中不存在。而且我无法找出它们到底应该包含什么。此外,边界框上的值只是左侧、顶部的值。
因此,如果您想计算左侧、顶部值,则必须使用其左侧、顶部值,并再次考虑最近定位的父项的位置
var rect = e.getClientRects();
var pseudoStyle = window.getComputedStyle(e, ':before');
//find the elements location in the page
//taking into account page scrolling
var top = rect.top + win.pageYOffset - document.documentElement.clientTop;
var left = rect.left + win.pageXOffset - document.documentElement.clientLeft;
//modify those with the pseudo element's to get its location
top += parseInt(pseudoStyle.top,10);
left += parseInt(pseudoStyle.left,10);
Run Code Online (Sandbox Code Playgroud)