如何将div定位到特定坐标

如何将div定位到特定坐标

给定一个HTML文档,任务是使用JavaScript设置网页上一个div元素在特定坐标的位置。我们将讨论一些技巧。

方法:

  • 首先设置元素的style.position属性。
  • 然后设置元素的style.top和style.left属性,即我们要定位的位置。

示例1: 在此示例中,我们将在文档的末尾将DIV设置到特定位置。

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to position a div at 
          specific coordinates?
    </title>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        Click on button to change 
        the position of the DIV
    </h3>
 
    <div id="GFG_DIV">
        This is Div box.
    </div>
    <br>
 
    <button onClick="GFG_Fun()">
        click here
    </button>
     
    <h3 id="GFG" style="color: green;"></h3>
 
    <script>
        let elm = document.getElementById("GFG");
 
        function GFG_Fun() {
            let x = 370;
            let y = 250;
            let el = document.getElementById('GFG_DIV');
            el.style.position = "absolute";
            el.style.left = x + 'px';
            el.style.top = y + 'px';
            elm.innerHTML =
                "Position of element is changed.";
        }
    </script>
</body>
 
</html>
HTML

输出:

如何将div定位到特定坐标

示例2: 在这个示例中,DIV被定位在文档的左上角。

<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to position a div at
        specific coordinates?
    </title>
 
    <style>
        #GFG_DIV {
            background: green;
            height: 50px;
            width: 80px;
            margin: 0 auto;
            color: white;
        }
    </style>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        Click on button to change 
        the position of the DIV.
    </h3>
 
    <div id="GFG_DIV">
        This is Div box.
    </div>
    <br>
 
    <button onClick="GFG_Fun()">
        click here
    </button>
     
    <h3 id="GFG" style="color: green;"></h3>
 
    <script>
        let elm = document.getElementById("GFG");
 
        function GFG_Fun() {
            let x = 0;
            let y = 0;
            let el = document.getElementById('GFG_DIV');
            el.style.position = "absolute";
            el.style.left = x + 'px';
            el.style.top = y + 'px';
            elm.innerHTML = "Position of element is changed.";
        }
    </script>
</body>
 
</html>
HTML

输出:

如何将div定位到特定坐标

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册