5👍
One solution is to bind an inline style that sets the absolute position of the <img>
:
-
Create an
<img>
tag:<img class="my-img">
-
Style it so it’s absolutely positioned:
.my-img { position: absolute; }
-
Bind its
style
to an object that sets thetop
(Y-coordinate) andleft
(X-coordinate). In the following example, we bindtop
to a data field namedimgTop
andleft
to one namedimgLeft
. When our component setsimgTop
, the<img>
‘stop
will be set to the same value; and similarly forleft
andimgLeft
. We’ll add theimgTop
andimgLeft
data fields later.<img class="my-img" :style="{ top: imgTop, left: imgLeft }">
-
Create a
<div>
to contain the<img>
. This container will represent the clickable area, where the<img>
can be moved.<div class="container"> <img class="my-img"> </div>
-
Style the container to be as large as the viewport (using
vw
andvh
length units):.container { width: 100vw; height: 100vh; }
-
Set a
click
-event handler on the container. We usev-on:EVENT=METHOD
to assign a method that handles the event (there’s also a shorthand syntax for this —@EVENT=METHOD
). We’ll add theonClick
method later.<div class="container" @click="onClick">
-
Create the
imgTop
andimgLeft
fields in your component’sdata
:extern default { data: () => ({ imgLeft: null, imgTop: null, }), }
-
Create the event-handler method in your component’s
methods
. Note the handler formats theMouseEvent.clientX
andMouseEvent.clientY
into pixel lengths (appendspx
), and assigns the results toimgLeft
andimgTop
.extern default { methods: { onClick(e) { this.imgLeft = `${e.clientX}px`; this.imgTop = `${e.clientY}px`; } } }
Demo:
new Vue({
el: '#app',
data: () => ({
imgLeft: null,
imgTop: null,
}),
methods: {
onClick(e) {
this.imgLeft = `${e.clientX}px`;
this.imgTop = `${e.clientY}px`;
}
}
})
.container {
width: 100vw;
height: 100vh;
}
.img {
position: absolute;
}
<script src="https://unpkg.com/vue@2.5.17"></script>
<div id="app">
<div class="container" @click.stop="onClick">
<img class="img"
src="//placekitten.com/100/100"
width="100"
alt="kitty"
:style="{top: imgTop, left: imgLeft}">
</div>
</div>
- [Vuejs]-Firebase RTDB startAfter() is not a function
- [Vuejs]-Vue Error when creating and hosting a website: This dependency was not found-