【问题标题】:How do I offset mouse position so that I can centre paragraphs when the user clicks?How do I offset mouse position so that I can centre paragraphs when the user clicks?
【发布时间】:2022-12-02 03:05:33
【问题描述】:

I am creating an interactive website where the user is able to click anywhere on the page and each paragraph will show up one by one. At the moment the paragraphs are displaying to the right of the click but i want the paragraph to be centred on the mouse position. Is there a way to do this?

Is there also a way to restrict the paragraphs from going off the screen as this creates a landscape scroll which i don't want, Any help would be appreciated.

const texts = [
  "Paragraph: 1",
  "Paragraph: 2",
  "Paragraph: 3",
  "Paragraph: 4",
  "Paragraph: 5",
  "Paragraph: 6",
  "Paragraph: 7",
  "Paragraph: 8",
  "Paragraph: 9",
  "Paragraph: 10"
];
const classes = [
  "red gray-bg font-1",
  "blue font-2",
   "red",
  "blue",
   "red",
  "blue",
   "red",
  "blue",
   "red",
  "blue",
  
];
// Keeps Track of Current Text
let currentParaIdx = 0;

document.addEventListener("click", (e) => {
  // Stop once All Texts are Displayed
  if (currentParaIdx === texts.length) return;

  const { clientX, clientY } = e; //get the click position

  //create the div
  const div = document.createElement("div");

  //set its text
  div.innerText = texts[currentParaIdx];


  //set its position and position style
  div.classList=classes[currentParaIdx];
  div.style.position = "absolute";
  div.style.left = clientX + "px";
  div.style.top = clientY + "px";
  currentParaIdx++;
  document.body.append(div); //add div to the page
});

This is the code I have so far

【问题讨论】:

    标签: javascript html onclick offset mouse-position


    【解决方案1】:

    You could use offsetWidth to center the element at your mouse position. Like clientX - half of your element's width.

    And the other thing, I think this is what you need: overflow

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2022-12-26
      • 2022-12-02
      • 2022-12-02
      • 2022-12-27
      • 2022-12-01
      • 2022-12-02
      • 2022-12-01
      • 2022-12-28
      相关资源
      最近更新 更多