简体   繁体   中英

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. I am stuck at the part where I am supposed to add the div that I have created to the 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.

Edit: This was bad way

Here You have answer: Instert element before </body> tag with 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>

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