javascript считывание позиции объекта и отображение по клику или сохранение в переменных - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь зачитать координаты x и y объекта. В идеале должна быть кнопка «onclick», которую можно нажать, а затем позиция будет считана и отображена.

Вот код и вот сайт: https://www.unisg.bplaced.net/JS/dragdrop3.html

То, что я хотел сделать, это

  • , зачитать расположите и сохраните их в переменных
  • , даже показав их в окне предупреждения. Но мне нужно было бы сохранить их в конечном итоге в моей программе опроса.

Вот код сайта пока

<html><head>
    <style>

    #container {
      width: 100%;
      height: 400px;
      background-image: url('http://www.unisg.bplaced.net/park2.png');
      background-repeat: no-repeat;
      background-size: contain;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 7px;
      touch-action: none;
    }


    #dragMe {
      width: 100px;
      height: 300px;
      background-image: url('http://www.unisg.bplaced.net/silhoutte3.png');
      background-size: 100px 300px;
      background-repeat: no-repeat;
        border-radius: 2em 2em 2em 2em;
        position: absolute;
        top: 10%;
        left: 20%;
    }
    
    #dropMe {
        width: 12em;
        height: 12em;
        padding: 0.5em;
        margin: 0 auto;
    }
    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script><style type="text/css">.as-console-wrapper { position: fixed; bottom: 0; left: 0; right: 0; max-height: 150px; overflow-y: scroll; overflow-x: hidden; border-top: 1px solid #000; display: none; }
.as-console { background: #e9e9e9; border: 1px solid #ccc; display: table; width: 100%; border-collapse: collapse; }
.as-console-row { display: table-row; font-family: monospace; font-size: 13px; }
.as-console-row:after { display: table-cell; padding: 3px 6px; color: rgba(0,0,0,.35); border: 1px solid #ccc; content: attr(data-date); vertical-align: top; }
.as-console-row + .as-console-row > * { border: 1px solid #ccc; }
.as-console-row-code { width: 100%; white-space: pre-wrap; padding: 3px 5px; display: table-cell; font-family: monospace; font-size: 13px; vertical-align: middle; }
.as-console-error:before { content: 'Error: '; color: #f00; }
.as-console-assert:before { content: 'Assertion failed: '; color: #f00; }
.as-console-info:before { content: 'Info: '; color: #00f; }
.as-console-warning:before { content: 'Warning: '; color: #e90 }
@-webkit-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@-moz-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@-ms-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
.as-console-row-code, .as-console-row:after { -webkit-animation: flash 1s; -moz-animation: flash 1s; -ms-animation: flash 1s; animation: flash 1s; }</style>
</head>
<body>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="container">
<div id="dragMe" class="ui-draggable ui-draggable-handle" style="position: relative; ">
<p>You</p>
</div>

<div id="dropMe"></div>
    <script type="text/javascript">
        $('#dragMe').draggable(
    {
        containment: $('body'),
        drag: function(){
            var position = $(this).position();
            var xPos = position.left;
            var yPos = position.top;
            $('#positionX').text('positionX: ' + xPos);
            $('#positionY').text('positionY: ' + yPos);
        },
         accept: '#dragMe',
        over : function(){
            $(this).animate({'border-width' : '5px',
                             'border-color' : '#0f0'
                            }, 500);
            $('#dragThis').draggable('option','containment',$(this));
        }
    
    });

function myFunction1() {
    alert("The position is" + position.left);
}

    </script>

<button onclick="myFunction1()">Click me</button>

<div class="as-console-wrapper"><div class="as-console"></div></div></body></html>

1 Ответ

0 голосов
/ 19 апреля 2020

Просто укажите один из атрибутов для идентификатора dragMe, поскольку вы указали обе позиции как абсолютные в css выше и относительные во встроенном css элемента.

И чтобы получить позицию в px добавить код как

<html><head>
    <style>

    #container {
      width: 100%;
      height: 400px;
      background-image: url('http://www.unisg.bplaced.net/park2.png');
      background-repeat: no-repeat;
      background-size: contain;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 7px;
      touch-action: none;
    }


    #dragMe {
      width: 100px;
      height: 300px;
      background-image: url('http://www.unisg.bplaced.net/silhoutte3.png');
      background-size: 100px 300px;
      background-repeat: no-repeat;
        border-radius: 2em 2em 2em 2em;
        position: absolute;
        top: 10%;
        left: 20%;
    }

    #dropMe {
        width: 12em;
        height: 12em;
        padding: 0.5em;
        margin: 0 auto;
    }
    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script><style type="text/css">.as-console-wrapper { position: fixed; bottom: 0; left: 0; right: 0; max-height: 150px; overflow-y: scroll; overflow-x: hidden; border-top: 1px solid #000; display: none; }
.as-console { background: #e9e9e9; border: 1px solid #ccc; display: table; width: 100%; border-collapse: collapse; }
.as-console-row { display: table-row; font-family: monospace; font-size: 13px; }
.as-console-row:after { display: table-cell; padding: 3px 6px; color: rgba(0,0,0,.35); border: 1px solid #ccc; content: attr(data-date); vertical-align: top; }
.as-console-row + .as-console-row > * { border: 1px solid #ccc; }
.as-console-row-code { width: 100%; white-space: pre-wrap; padding: 3px 5px; display: table-cell; font-family: monospace; font-size: 13px; vertical-align: middle; }
.as-console-error:before { content: 'Error: '; color: #f00; }
.as-console-assert:before { content: 'Assertion failed: '; color: #f00; }
.as-console-info:before { content: 'Info: '; color: #00f; }
.as-console-warning:before { content: 'Warning: '; color: #e90 }
@-webkit-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@-moz-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@-ms-keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
@keyframes flash { 0% { background: rgba(255,240,0,.25); } 100% { background: none; } }
.as-console-row-code, .as-console-row:after { -webkit-animation: flash 1s; -moz-animation: flash 1s; -ms-animation: flash 1s; animation: flash 1s; }</style>
</head>
<body>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="container">
<div id="dragMe" class="ui-draggable ui-draggable-handle" style="position: relative; ">
<p>You</p>
</div>

<div id="dropMe"></div>
    <script type="text/javascript">
        $('#dragMe').draggable(
    {
        containment: $('body'),
        drag: function(){
            var position = $(this).position();
            var xPos = position.left;
            var yPos = position.top;
            $('#positionX').text('positionX: ' + xPos);
            $('#positionY').text('positionY: ' + yPos);
        },
         accept: '#dragMe',
        over : function(){
            $(this).animate({'border-width' : '5px',
                             'border-color' : '#0f0'
                            }, 500);
            $('#dragThis').draggable('option','containment',$(this));
        }

    });

$(document).ready(function(){
  $("button").click(function(){
    var x = $("#dragMe").position();
    alert("Top position: " + x.top + " Left position: " + x.left);
  });
});

    </script>

<button>Click me</button>

<div class="as-console-wrapper"><div class="as-console"></div></div></body></html>

Здесь код jQuery даст вам необходимые позиции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...