簡體   English   中英

將鼠標移動附加到內部帶有 iframe 的 div

[英]Attach mouse movement to a div with Iframe inside

在我的JS代碼中,我在mousemovetouchmove上添加了一個EventListener ,這使得我的div跟隨cursor (像這樣)

CSS

  <style>
    body {
padding: 0;
margin: 0;
height: 100vh;
background: linear-gradient(135deg, #8fc7f1, #7173f5);
overflow: hidden;
}
#my-div {
width: 300px;
height: 250px;
background-color: #ffffff;
position: absolute;
}
</style>

HTML:

<div id="my-div">
  <h1>Hello</h1>
</div>

JAVASCRIPT:

let myDiv = document.getElementById("my-div");
//Detect touch device
function isTouchDevice() {
  try {
    //We try to create TouchEvent. It would fail for desktops and throw error
    document.createEvent("TouchEvent");
    return true;
  } catch (e) {
    return false;
  }
}

const move = (e) => {
  //Try, catch to avoid any errors for touch screens (Error thrown when user doesn't move his finger)
  try {
    //PageX and PageY return the position of client's cursor from top left of screen
    var x = !isTouchDevice() ? e.pageX : e.touches[0].pageX;
    var y = !isTouchDevice() ? e.pageY : e.touches[0].pageY;
  } catch (e) {}
  //set left and top of div based on mouse position
  myDiv.style.left = x - 150 + "px";
  myDiv.style.top = y - 120 + "px";
  // myDiv.style.opacity = 0;
  // console.log(myDiv.getBoundingClientRect())
};
//For mouse
document.addEventListener("mousemove", (e) => {
  move(e);
  console.log("Mouse")
});

//For touch
document.addEventListener("touchmove", (e) => {
  move(e);
});

JSFIDDLE 代碼

我想要做的是在我的div中添加一個iframe並且div應該仍然跟隨cursor ,但是當我在div中添加iframe時, EventListener停止工作並且我的div停止跟隨光標。 我不確定問題是什么。 (像這樣)

<div id="my-div">
    <iframe src="https://example.com/" width="300" height="250">
</div>

帶有 IFRAME 的 JSFIDDLE 代碼

任何幫助和建議表示贊賞!

您忘記了結束iframe標記

<div id="my-div">
  <iframe src="https://example.com/" width="300" height="250"></iframe>
</div>

我認為您應該將 div 的位置更改為相對,將 iframe 的位置更改為絕對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM