[英]How to add a div into html code using Javascript
I am trying to create a function that is supposed to take the mouse coordinates and draw a small radius using their values and inserting them into CSS left and top positions.我正在尝试创建一个函数,该函数应该获取鼠标坐标并使用它们的值绘制一个小半径并将它们插入到 CSS 左侧和顶部位置。 I am stuck at the part where I am supposed to add the div that I have created to the html.我被困在我应该将我创建的 div 添加到 html 的部分。 Please forgive me if I am not being clear enough.如果我说的不够清楚,请见谅。
<script type="text/javascript">
function getcoord(event) {
var x=event.clientX ;
var y=event.clientY ;
follow(x,y);
function follow(xcor,ycor) {
folowHTML =
'<div style="'background-color:red;width:30px;height:30px;'
+'border-radius:30px;position:absolute;left:''+xcor;'top:'+ycor';">'
+'</div>';
};}
</script>
<body onmouseover="getcoord(event);">
</body>
Maybe try add this line:也许尝试添加这一行:
document.body.innerHtml = folowHTML + document.body.innerHtml;
Also You should probably change position absolute
to fixed
I think.另外,我认为您应该将absolute
位置更改为fixed
位置。
Here You have answer: Instert element before </body> tag with vanilla JavaScript在这里你有答案: 在 </body> 标签之前使用 vanilla JavaScript 插入元素
You could try something like this...你可以试试这样的...
<style>
#follow {
background-color: #fff;
border:1px solid red;
border-radius: 50%;
height: 20px;
margin:-10px 0 0 -10px;
position: absolute;
width: 20px;
z-index: 10;
}
</style>
<script>
function initFollow(){
var follow = document.createElement('div');
follow.setAttribute('id','follow');
document.getElementsByTagName("body")[0].appendChild(follow);
window.addEventListener('mousemove', function(e) {
var left = e.pageX + 'px',
top = e.pageY + 'px';
follow.style.left = left;
follow.style.top = top;
}, false);
}
window.addEventListener('load',initFollow,false);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.