JS做放大缩小的效果时,JS为什么在HEAD中没效果?

先上代码: //我运行的时候会取消掉注释的

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>08work</title>
  <!-- 111
    <script>
    window.onload = function(){
        var imgElement = document.getElementById("outInPic");
        imgElement.width=500;
        function zoomIn(){
            imgElement.width-=100;
        }
        function zoomOut(){
            imgElement.width+=100;
        }

    }
    </script>
    -->
</head>
<body>
    <img src="鸣人1.jpg" alt="鸣人" title="漩涡鸣人" id="outInPic" width="300">  
    <button onclick="zoomIn()">缩小</button>
    <button onclick="zoomOut()">放大</button>
    <!--  222
<script>
    var imgElement = document.getElementById("outInPic");
    imgElement.width=500;
    function zoomIn(){
        imgElement.width-=100;
    }
    function zoomOut(){
        imgElement.width+=100;
    }

</script>
-->
</body>
</html>

百度过后说是浏览器的加载顺序,然后尝试了
window.onload = function(){}
$(document).ready(function){}
结果没什么用..
只有在将js放在body后才有用(主要是 img 后面,在button前面没关系)。

问:到底怎么做才可以让它在head中有效果... window.onload这个为什么会没效果(因为大家都说加这个就可以了)

阅读 3.2k
4 个回答

作用域的问题,另外说一句你这写法很有问题

clipboard.png

注意通过属性绑定事件的问题:

  • window.onload 是事件在页面元素渲染完毕后的回调

  • zoomInzoomOut 是在 window.onload 中定义的函数

  • 在渲染 button 时同时定义了 onclick 属性,这时 zoomInzoomOut 还没有定义,导致调用报错,按钮失效。

  • 按你的需求,解决方案是在 window.onload 之前定义 zoomInzoomOut。也就是将其放在 window.onload 外面。

这是因为浏览器加载html页面,是从上到下一行一行加载渲染的。在load的时候,js在前面,outInPic这个id元素还没有,所以放head里时imgElement是为null的

<script>
    var imgElement = null;//全局
    window.onload = function(){
        imgElement = document.getElementById("outInPic");
        //console.log(imgElement);
        imgElement.width=500;
    }
    function zoomIn(){
        imgElement.width-=100;
    }
    function zoomOut(){
        imgElement.width+=100;
    }
    </script>

把zoomIn和zoomOut两个函数放window.onload函数外,imgElement变量定义成全局

你把 zoomIn()zoomOut() 定义在 window.onload() 里面的话,他们是局部函数,全局访问不到,包括 button 元素的 onclick 事件处理器属性也无法访问。如果要把它放在 head 里面的话一个可能可以的办法是

window.onload = function(){
    var imgElement = document.getElementById("outInPic");
    imgElement.width = 500;
    window.zoomIn = function zoomIn() {
        imgElement.width -= 100;
    };
    window.zoomOut = function zoomOut() {
        imgElement.width += 100;
    };
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题