简体   繁体   中英

how to move a image with arrow keys and get id of behind div in javascript?

I have done successfully moved a image with arrow keys but now i want getting id behind the moved image. And here i want all div id when image overlap.

html

<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
<img id="image" src="http://placekitten.com/69/69" style="position:absolute;left:0; top:0; z-index: 1;" height="15" width="15">

css

body{background:yellow;}
#box2, 
#box3, 
#box4, 
#box5 {
  width: 50px;
  height: 50px;
  background: greenyellow;
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 2 
}

#box3 {
  top: 150px;
  left: 150px; 
}

#box4 {
  top: 50px;
  left: 250px;
}

Please check demostration link

https://jsfiddle.net/36y0ztn9/1/

要获取ID,您可以在JavaScript文件中使用document.querySelector('#idname) or document.getElementById('idname')

Following up to my comments above,

document.elementFromPoint only gets the top most element - mozilla docs , which here is the image itself, so use a work around like setting display:none or pointer-events:none to the image to make the box as the top most elem and get the box Id. Then reset the value back.

Check this working fiddle, where I made some modifications to yours : https://jsfiddle.net/y6xsnc8h/1

Also Check this answer for a reusable function : https://stackoverflow.com/a/22428553/7314900

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM