这是我写的一个javascript程序,但想了很久都不知道哪里错了

 <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div>
            <img id="pic" src="测试用图片/Watch-Dogs.jpg" height="200px" width="200">
        </div>
        <div>
        <form>
            <button onclick="changposition(relative)">相对定位</button>
            <button onclick="changposition(absolute)">绝对定位</button>
        </form>
        </div>
    </body>
</html>
<script type="text/javascript">
    function changposition(type){
        var img=document.getElementById("pic");
        img.style.position=type;
        img.style.left=400px;
        img.style.top=500px;
    }
</script>

我的目的很简单按“相对定位”,图片就会以相对定位的形式定位,按“绝对定位”,图片会以绝对定位的形式定位,但现在按两个按钮都没有用了,我想了很久都不知道哪里错了....

单位要注意加上,字符要用引号括起,不要使用button标签,标准浏览器下是submit按钮,会提交表单,改为input type=button或者去掉form标签

 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <div>
        <img id="pic" src="测试用图片/Watch-Dogs.jpg" height="200px" width="200">
    </div>
    <div>

            <button onclick="changposition('relative')">相对定位</button>
            <button onclick="changposition('absolute')">绝对定位</button>

    </div>
</body>
</html>
<script type="text/javascript">
    function changposition(type){
        var img=document.getElementById("pic");
        img.style.position=type;
        img.style.left='400px';
        img.style.top='500px';
    }
</script>

代码看不清楚,建议你调试下

代码逻辑正确吗?按钮的点击事件执行了吗?浏览器开发者模式F12调试下看有没有报错。

img.style.position=type
这里直接写死看看是否有效







相对定位
绝对定位


上面的html代码看不到,我发多一次吧

图片说明

就是这些代码

把form去掉,有form的话提交的是表单

我帮你改好了,可以运行了
问题出在没在‘号。如400px或400.这里得写成"400px"或’400‘(单引号)

 <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript">
      function changposition(type){
       var img=document.getElementById("pic");
        img.style.position=type;
        img.style.left='400px';
        img.style.top='500px';
   }
</script>
    </head>
    <body>
        <div>
            <img id="pic" src="1.png" height="200px" width="200px">
        </div>
        <div>
        <div>
            <button onclick="changposition('relative')">相对定位</button>
            <button onclick="changposition('absolute')">绝对定位</button>
        </div>
        </div>
    </body>
</html>