Хороший вопрос, мне пришлось go вернуться к javascript основам. К счастью, я нашел ключ - есть offsetTop, offsetLeft
свойства!
Таким образом, в этом скрипте, в mousedown, мы получаем местоположение щелчка события, затем вычитаем позицию смещения элемента article.
Положение смещения относится к тому, как далеко целевой элемент находится от начала документа.
РЕДАКТИРОВАТЬ: Для обработки вертикальной позиции прокрутки внутри статьи, я добавил article.scrollTop
при вычислении.
Запустите демонстрацию ниже.
const article = document.querySelector(`article`);
var x;
var y;
article.addEventListener('mousedown', function() {
x = event.clientX;
y = event.clientY;
y = y - article.offsetTop + article.scrollTop - 5.5;
x = x - article.offsetLeft + 1;
})
article.addEventListener('mouseup', function() {
var result = window.getSelection().toString();
const oldMark = document.querySelector(`.mark`);
const body = document.querySelector(`body`);
if (oldMark) {
article.removeChild(oldMark);
}
window.getSelection().empty()
if (result) {
let mark = document.createElement('mark');
mark.innerText = `${result}`;
mark.classList.add('mark');
mark.setAttribute("style", `top:${y}px; left:${x}px;`);
article.appendChild(mark);
}
});
main {
display: flex;
flex-direction: column;
height: 100vh;
align-items: center;
justify-content: center;
}
article {
max-height: 50%;
overflow: scroll;
flex: 0 0 50vw;
position: relative;
}
.mark {
position: absolute;
top: 50%;
left: 50%;
}
<main>
<article>
<p>I'm trying to build something like the highlight feature in Medium.<br> The issue is that in the click event I need to add an element that will be in a <strong>position absolute</strong> to his parent and not the body since the parent is <strong>overflow: scroll;<strong><br>
How can I find those x and y conditions?
</p>
<p>I'm trying to build something like the highlight feature in Medium.<br>
The issue is that in the click event I need to add an element that will be in a <strong>position absolute</strong> to his parent and not the body since the parent is <strong>overflow: scroll;<strong><br>
How can I find those x and y conditions?
</p>
<p>I'm trying to build something like the highlight feature in Medium.<br>
The issue is that in the click event I need to add an element that will be in a <strong>position absolute</strong> to his parent and not the body since the parent is <strong>overflow: scroll;<strong><br>
How can I find those x and y conditions?
</p>
</article>
</main>