将js脚本移至外部文件 [英] Move js script to external file

查看:96
本文介绍了将js脚本移至外部文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在div中有以下代码,以在单击他的移动按钮时移动div:

I have the following code in a div to move the div when clicking on he move button:

    <input id="move1" class="smallButtonidle" type="button" value="M" style="top: 0px; left: 0px; float: left;"  />
<script type="text/javascript">
var isDown1 = false;
document.getElementById('move1').addEventListener('mousedown', function(e1)
 {
    isDown1 = true;
    offset = [document.getElementById('jsmolwindow1').offsetLeft - e1.clientX,
        document.getElementById('jsmolwindow1').offsetTop - e1.clientY];
}, true);
window.addEventListener('mouseup', function() {
    isDown1 = false;
}, true);
window.addEventListener('mousemove', function(event) {
    if (isDown1) {
       mousePosition = {
          x : event.clientX,
         y : event.clientY
   };
        document.getElementById('jsmolwindow1').style.left = (mousePosition.x + offset[0]) + 'px';
        document.getElementById('jsmolwindow1').style.top  = (mousePosition.y + offset[1]) + 'px';
    }
}, true);
</script>

我想将此js脚本移至外部文件以阐明我的html

I would like to move this js script to an external file to clarify my html

我通过以下方式修改html代码:

I modify my html code the following way :

 <input id="move1" class="smallButtonidle" type="button" value="M" style="top: 0px; left: 0px; float: left;"  onclick="move1js()"/>

并放入一个include js外部文件:

And put in an include js external file:

function move1js()
{
var isDown1 = false;
document.getElementById('move1').addEventListener('mousedown', function(e1)
 {
    isDown1 = true;
    offset = [document.getElementById('jsmolwindow1').offsetLeft - e1.clientX,
        document.getElementById('jsmolwindow1').offsetTop - e1.clientY];
}, true);
window.addEventListener('mouseup', function() {
    isDown1 = false;
}, true);
window.addEventListener('mousemove', function(event) {
    if (isDown1) {
       mousePosition = {
          x : event.clientX,
         y : event.clientY
   };
        document.getElementById('jsmolwindow1').style.left = (mousePosition.x + offset[0]) + 'px';
        document.getElementById('jsmolwindow1').style.top  = (mousePosition.y + offset[1]) + 'px';
    }
}, true);
}

这样做,我的移动按钮停止工作.我不明白为什么.

Doing so my move button stop working. I don't understand why.

有什么想法吗?

推荐答案

解决方案的步骤是:

  1. 创建一个javascript文件(扩展名为.js的文件).让我们 假设文件是​​moveDiv.js
  2. 按原样将所有JavaScript代码移动到此新创建的文件中 除了 <script>& </script>标签.
  3. 在您的HTML文件中将此文件引用为

  1. Create a javascript file (a file with extension .js). Lets suppose the file is moveDiv.js
  2. Move all the javascript code into this newly created file as it is except <script> & </script> tags.
  3. Give reference to this file in your HTML file as

<script src="moveDiv.js" type="text/javascript"></script>

这应该再次开始移动您的按钮.

This should start moving your button again.

这篇关于将js脚本移至外部文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆