使用JavaScript移动页面上的按钮 [英] Move buttons on a page using JavaScript

查看:99
本文介绍了使用JavaScript移动页面上的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的按钮可以移动,但奇怪的是,我无法弄清楚偏移量是否有问题。



我希望我的按钮可以随鼠标光标移动,但现在它的移动方式并不是我想要的,有时会消失。

另外,创建的新按钮重叠,我不知道如何解决这个问题,并且有更好的外观。



  var coorA; var coorB; var btn = null; function mousedown(){if(event.target.tagName ===BUTTON ){btn = event.target; coorA = btn.offsetTop; coorB = btn.offsetLeft; }} function mouseup(){btn = null;} function mousemove(){if(btn!== null){btn.style.top =(event.clientY  -  coorA)+px; btn.style.left =(event.clientX  -  coorB)+px; }} function createButton(){var button = document.createElement(BUTTON); var msg = document.getElementById(word).value; if(msg.length> 0){var t = document.createTextNode(msg); button.appendChild(T); document.body.appendChild(按钮); document.getElementsByTagName(body)[0] .addEventListener(mousedown,mousedown); document.getElementsByTagName(body)[0] .addEventListener();} document.getElementById(word)。value =;} document.getElementsByTagName (mousemove,mousemove); document.getElementsByTagName(body)[0] .addEventListener(mouseup,mouseup);  

  body {background-color:black;}#word {padding:10px 30px; font-size:14px;} button {position:absolute; background-color:#e7e7e7;颜色:#000; font-weight:700; padding:10px 30px; font-size:14px; border:1px solid gray;}#add {position:relative; background-color:#e7e7e7;颜色:#000; font-weight:700; padding:10px 30px; font-size:14px;}  

<!DOCTYPE html> ;< - 要更改此许可证标题,请在项目属性中选择许可证标题。要更改此模板文件,请选择工具|模板并在编辑器中打开模板.-->< html> < HEAD> <标题>诗歌-yuc217< /标题> < meta charset =UTF-8> < meta name =viewportcontent =width = device-width,initial-scale = 1.0> < /头> <身体GT; < DIV> <形式> < input id =wordtype =textname =word> < input id =addtype =buttonvalue =Add Wordonclick =createButton()> <峰; br> < /形式> < button type =button>此< / button> < / DIV>请在此处输入代码< / body>< / html>

解决方案

在评论中回答您的问题:


非常感谢!对于什么事件实际上
指的是什么,我仍然有些困惑。从我所了解到的,事件就是页面上的所有行为。
这还不是很清楚......

在你的代码中你引用了事件对象,但没有作为参数传递它。我相信你可能会因此而产生混淆。好吧,我很好奇自己,哦,男孩,我去了兔子洞... ...



我会尽量简单&一般,因为我自己还没有完全包装我对此的理解。



好的,所以浏览器中有不同类型的事件。你可能知道一些标准的,比如click,onload,keydown等等。如果你希望你的代码在发生这样的事件时做某些事情,你会选择一个DOM元素,比如< button> < div> etc(一般来说,因为也有非DOM相关活动,你可以在这里阅读所有关于 https://developer.mozilla.org/ en-US / docs / Web / Events )然后,您将此元素附加到一个函数,该函数将在触发上述事件时调用。



是附加这样一个函数的不同方式(它也被称为事件处理程序或事件处理程序事件处理程序)当附加事件处理程序时,称为 EventListener接口正在实现中,一个通过事件触发的函数将获得一个参数,一个Event对象,由接口提供( https://www.w3.org/TR/2013/WD-DOM-Level-3 -Events-20131105 /#glossary-event-handler )。



但是!!!如果使用内联方法附加事件,即< a onclick =myFunc(); /> 只有在函数内写入event时,函数才会收到参数(事件),即< a onclick =myFunc(event); />



您可以观察到这种奇怪的行为以及在此JSFiddle中附加的不同类型的事件:

https://jsfiddle.net/duwed8kg/



我不确定为什么会发生这种情况,但对于新问题来说这是一个很好的主题。



PS,关于您的代码和主要问题(我只提供了代码,没有解释) - 它以不同的方式出现问题(内联事件附加,通过ex标记名称进行元素选择),我专注于通过对代码进行最少更改来解决问题/ style,但请注意它。



var coorA; var coorB; var btn = null; var lastMouseX; var lastMouseY; function mousedown (){if(event.target.className.indexOf(listButton)> -1){btn = event.target; if(btn.style.top ===|| btn.style.left ===){btn.style.position =absolute; btn.style.top = btn.offsetTop +px; btn.style.left = btn.offsetLeft +px; } coorA = btn.offsetTop; coorB = btn.offsetLeft; }} function mouseup(){btn = null;} function mousemove(){if(btn!== null){btn.style.top = parseInt(btn.style.top)+(event.clientY - lastMouseY)+ PX; btn.style.left = parseInt(btn.style.left)+(event.clientX - lastMouseX)+px; } lastMouseX = event.clientX; lastMouseY = event.clientY;} function createButton(){var button = document.createElement(BUTTON); var msg = document.getElementById(word).value; if(msg.length> 0){var t = document.createTextNode(msg); button.appendChild(T); button.classList.add( listButton); document.getElementsByClassName( 容器)[0] .appendChild(按钮); document.getElementsByTagName(body)[0] .addEventListener(mousedown,mousedown); document.getElementsByTagName(body)[0] .addEventListener();} document.getElementById(word)。value =;} document.getElementsByTagName (mousemove,mousemove); document.getElementsByTagName(body)[0] .addEventListener(mouseup,mouseup); document.getElementById(add).addEventListener(click,createButton);

body {background-color:black;}。container {position:relative ; height:1000px;}#word {padding:10px 30px; font-size:14px;} button {background-color:#e7e7e7;颜色:#000; font-weight:700; padding:10px 30px; font-size:14px; border:1px solid gray;}。listButton {margin-right:5px; margin-top:5px; float:left;}#add {position:relative; background-color:#e7e7e7;颜色:#000; font-weight:700; padding:10px 30px; font-size:14px;}

<!DOCTYPE html> ;< - 要更改此许可证标题,请在项目属性中选择许可证标题。要更改此模板文件,请选择工具|模板并在编辑器中打开模板.-->< html> < HEAD> <标题>诗歌-yuc217< /标题> < meta charset =UTF-8> < meta name =viewportcontent =width = device-width,initial-scale = 1.0> < /头> <身体GT; < div class =container> <形式> < input id =wordtype =textname =word> < input id =addtype =buttonvalue =Add Word> <峰; br> < /形式> < button type =buttonclass =listButton>此< / button> < / DIV>在此输入代码< / body>< / html>

My button can move, but weirdly, I can't figure out if it's something wrong with the offset.

I want my buttons to move with my mouse cursor, but now it's moving not in a way that I want and sometimes it disappears.

Also, the new buttons created are overlapping, I don't know how to solve that and have a nicer look.

var coorA;
var coorB;
var btn = null;

function mousedown() {
    if (event.target.tagName === "BUTTON") {
        btn = event.target;
        coorA = btn.offsetTop;
        coorB = btn.offsetLeft;
    }
}

function mouseup() {
    btn = null;
}

function mousemove() {
    if (btn !== null) {
        btn.style.top = (event.clientY - coorA) + "px";
        btn.style.left = (event.clientX - coorB) + "px";
    }
}

function createButton() {
    var button = document.createElement("BUTTON");
    var msg = document.getElementById("word").value;
    if (msg.length > 0) {
        var t = document.createTextNode(msg);
        button.appendChild(t);
        document.body.appendChild(button);
    }
    document.getElementById("word").value = "";
}
document.getElementsByTagName("body")[0].addEventListener("mousedown", mousedown);
document.getElementsByTagName("body")[0].addEventListener("mousemove", mousemove);
document.getElementsByTagName("body")[0].addEventListener("mouseup", mouseup);

body {
    background-color: black;
}
#word {
    padding: 10px 30px;
    font-size: 14px;
}

button {
    position: absolute;
    background-color: #e7e7e7;
    color: #000;
    font-weight: 700;
    padding: 10px 30px;
    font-size: 14px;
    border: 1px solid gray;
}

#add {
    position: relative;
    background-color: #e7e7e7;
    color: #000;
    font-weight: 700;
    padding: 10px 30px;
    font-size: 14px;
}

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Poetry-yuc217</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        

    </head>
    <body>
        <div>
            <form>
                <input id = "word" type = "text" name = "word">
                <input id = "add" type = "button" value = "Add Word" onclick = "createButton()">
                <br>
                
            </form>
            <button type="button" >this</button>
               

        </div>


        
   

enter code here
    </body>
</html>

解决方案

Answer to your question in the comments:

Thanks so much! I am still little confused about what "event" actually refers to. From what I learned, event is all the actions on the page. And that is not so clear...

In your code you have referenced the event object but haven't passed it as an argument. I believe you confusion may stem from this. Well, I was curios myself, and oh boy, down the rabbit hole I went...

I'll try to be as simple & general as I can, as I myself have yet completely wrapped my understanding of this.

OK, so there are different types of events in the browser. You probably know some of the standard ones such as "click, "onload", "keydown" etc. If you wish your code to do something when such an event occurs, you'll choose a DOM element such as <button>, <div> etc (generally speaking, because there are also non-DOM related events, you can read all about it here https://developer.mozilla.org/en-US/docs/Web/Events). You then attach this element to a function that will be invoked when the said event is triggered.

There are different ways of attaching such a function (which BTW is also called the event handler or event listener). When attaching the event handler, something called the EventListener interface is being implemented. A function that was triggered through an event will get an argument, a Event object, courtesy of the interface (https://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#glossary-event-handler).

BUT!!! If you attach an event using the inline method i.e <a onclick="myFunc();" /> your function will receive the argument (the event) only if "event" is written inside the function, i.e <a onclick="myFunc(event);" />.

You can observe this odd behavior and the different types of event attaching in this JSFiddle:

https://jsfiddle.net/duwed8kg/

I am uncertain as to why this happens, but it's a damn good subject for new question.

P.S, Regarding your code and the main question (for which I only provided the code, sans an explanation) -- It is problematic in different ways (the inline event attaching, element selection via tag names for ex), I focused on solving your problem with minimal changes to your code/style, but please be aware of it.

var coorA;
var coorB;
var btn = null;
var lastMouseX;
var lastMouseY;

function mousedown() {
    if (event.target.className.indexOf("listButton") > -1) {
        btn = event.target;
        if(btn.style.top === "" || btn.style.left === "") {
          btn.style.position = "absolute";
          btn.style.top = btn.offsetTop + "px";
          btn.style.left = btn.offsetLeft + "px";
        }
        coorA = btn.offsetTop;
        coorB = btn.offsetLeft;
    }
}

function mouseup() {
    btn = null;
}

function mousemove() {
    if (btn !== null) {
        btn.style.top = parseInt(btn.style.top) + (event.clientY - lastMouseY) + "px";
        btn.style.left = parseInt(btn.style.left) + (event.clientX - lastMouseX) + "px";
    }
    lastMouseX = event.clientX;
    lastMouseY = event.clientY;
}

function createButton() {
    var button = document.createElement("BUTTON");
    var msg = document.getElementById("word").value;
    if (msg.length > 0) {
        var t = document.createTextNode(msg);
        button.appendChild(t);
        button.classList.add("listButton");
        document.getElementsByClassName("container")[0].appendChild(button);
    }
    document.getElementById("word").value = "";
}
document.getElementsByTagName("body")[0].addEventListener("mousedown", mousedown);
document.getElementsByTagName("body")[0].addEventListener("mousemove", mousemove);
document.getElementsByTagName("body")[0].addEventListener("mouseup", mouseup);
document.getElementById("add").addEventListener("click", createButton);

body {
    background-color: black;
}

.container {
  position:relative;
  height:1000px;
}

#word {
    padding: 10px 30px;
    font-size: 14px;
}

button {
    background-color: #e7e7e7;
    color: #000;
    font-weight: 700;
    padding: 10px 30px;
    font-size: 14px;
    border: 1px solid gray;
}

.listButton {
    margin-right: 5px;
    margin-top: 5px;
    float: left;
}
#add {
    position: relative;
    background-color: #e7e7e7;
    color: #000;
    font-weight: 700;
    padding: 10px 30px;
    font-size: 14px;
}

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Poetry-yuc217</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        

    </head>
    <body>
        <div class="container">
            <form>
                <input id = "word" type = "text" name = "word">
                <input id = "add" type = "button" value = "Add Word">
                <br>
                
            </form>
            <button type="button" class="listButton">this</button>
               

        </div>


        
   

enter code here
    </body>
</html>

这篇关于使用JavaScript移动页面上的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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