未加星标

Positioning a div element with x and y offset of another element

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

Good day! With javascript I am trying to create a function which will create a div element with a small offset from the triggering button / div. The good news is that at least as much elements are created as much as one of the effects is triggered. The bad news is that the styling of the X and Y of the div is not working properly.

The code is actually pretty short, I have posted some comments to make it more readable, I don't get any errors when running the function so I really have no idea where the error is.

<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <style> /*What will be created*/ .box { width: 30px; height: 30px; background-color:red; } /*The positioning for the first button*/ .btm12 { margin-left:50%; margin-top:5% } /*The positioning for the second button*/ .btm1 { margin-left:30%; margin-top:10% } </style> </head> <body> <button id="btn" onclick="createBox()" class="btm1">Click me</button><br /> <button id="btn2" onclick="createBox()" class="btm12">Click me</button> </body> </html> <script> document.getElementById("btn").onclick = function () { createBox(this.id); }; document.getElementById("btn2").onclick = function () { createBox(this.id); }; function createBox(IDI) { //get reference to the element var element = document.getElementById(IDI); //a way we can acces the X and Y coordinates var position = element.getBoundingClientRect(); var x = position.left; var y = position.top; //create, style and set the X/Y of the the div element var box = document.createElement("div"); box.className = "box"; box.style.left = x; box.style.top = y -10; box.style.position = "absolute"; //Apend the element to the body document.body.appendChild(box); } </script>

Problem courtesy of: Bloodcount

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Positioning a div element with x and y offset of another element
本站链接:https://www.codesec.net/view/611543.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(64)