我希望将类为“.absolute”的div内的红色“Aliquam”文本放在“.aliquam-span”内的(蓝色)“Aliquam”文本的确切位置上,包括在浏览器调整大小时。
我尝试了几种不同的方法来做这件事,但都没有太多的运气-希望有人在这里可以帮助。
不幸的是,将文本嵌套为span的子级不是一个选项。
谢谢大家!
let aliquam = document.querySelector('.aliquam-span')
let aliquamAbsolute = document.querySelector('.red-text')
let aliquamRect = aliquam.getBoundingClientRect()
let aliquamAbsoluteRect = aliquamAbsolute.getBoundingClientRect()
let xOffset = aliquamRect.left - aliquamAbsoluteRect.left
let yOffset = aliquamRect.top - aliquamAbsoluteRect.top
console.log({xOffset})
aliquamAbsolute.style.left = `${xOffset}px`
aliquamAbsolute.style.top = `${yOffset}px`
.container {
width: 100%;
max-width: 60rem;
margin-left: auto;
margin-right: auto;
}
p {
font-size: 1.5rem;
}
.wrap {
position: relative;
}
.absolute {
position: absolute;
inset: 0;
}
.red-text {
position: relative;
color: red;
left: '200px';
}
.aliquam-span {
color: blue;
}
<div class="container">
<div class="wrap">
<p>Maecenas a finibus sapien. Duis pulvinar ligula vel arcu cursus, in euismod nunc iaculis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Fusce facilisis quis libero nec bibendum. Donec suscipit eros sit amet ex condimentum ullamcorper. Aliquam dictum, risus id pharetra congue, nisl nisi facilisis enim, sit amet facilisis nunc diam condimentum eros. Aenean euismod turpis id enim commodo sagittis. <span class="aliquam-span">Aliquam</span> eget dolor eget nulla tempus imperdiet. Praesent gravida, nisl quis malesuada faucibus, orci purus ultrices velit, ut porttitor libero ante at nisl. Duis eget convallis risus. Nunc vitae orci non tellus ultricies vestibulum in a augue. Vestibulum hendrerit leo ac nunc rutrum imperdiet. Integer sem tellus, maximus vel interdum ut, accumsan vel orci. Mauris maximus leo vitae felis dapibus euismod. Nulla facilisi. Donec ac ullamcorper justo.</p>
<div class="absolute">
<p class="red-text">Aliquam</p>
</div>
</div>
</div>
3条答案
按热度按时间nr7wwzry1#
您应该将
div
设置为绝对定位的对象,因此选择.absolute
而不是.red-text
。2g32fytz2#
对我很有效,试试看:
twh00eeo3#
GSAP的人帮了我这个忙!
这里有三个不同的答案:
https://greensock.com/forums/topic/35705-tracking-position-of-a-text-span-with-javascript/