光标应位于 .click() 上图像的中心

我正在举这个小例子,我试图将图像置于光标的中心,基本上,当您单击时,光标应该位于图像的中心。由于我是初学者,我真的不知道如何才能实现这一目标。也许是通过使用类似的东西$(".theImg").height,但我认为我做错了,因为它不起作用。也许我必须使用transform...


$(document.body).click(function(event) {

        x = event.pageX;

        y = event.pageY;

        console.log(x +", "+ y);

        console.log(('theImg').height);


        $(".paysage") .css({'position' : 'absolute', 'top': y, 'left' : x})

                      .prepend($('<img>',{  class:'theImg',

                                            src:'https://www.30millionsdamis.fr/uploads/pics/conseils-erreurs-chat-1171.jpg'})) 

        $(".theImg").prev().remove();       

              

});

body{

  width: 100vw;

  height: 100vh

}


.theImg{

  width :20em;

  height: auto;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class = "paysage"> </div>


慕丝7291255
浏览 76回答 1
1回答

慕慕森

使用transformcss 属性imgtransform: translate(-50%, -50%)$(document.body).click(function(event) {  x = event.pageX;  y = event.pageY;  console.log(x + ", " + y);  console.log(('theImg').height);  $(".paysage").css({      'position': 'absolute',      'top': y,      'left': x    })    .prepend($('<img>', {      class: 'theImg',      src: 'https://www.30millionsdamis.fr/uploads/pics/conseils-erreurs-chat-1171.jpg'    }))  $(".theImg").prev().remove();});body {  width: 100vw;  height: 100vh}.theImg {  width: 20em;  height: auto;  transform: translate(-50%, -50%)}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="paysage"></div>

潇湘沐

将此带有规则的选择器添加到您的 css 中:.paysage {&nbsp; transform: translate(-50%, -50%);}有必要吗?$(document.body).click(function(event) {&nbsp; &nbsp; &nbsp; &nbsp; x = event.pageX;&nbsp; &nbsp; &nbsp; &nbsp; y = event.pageY;&nbsp; &nbsp; &nbsp; &nbsp; console.log(x +", "+ y);&nbsp; &nbsp; &nbsp; &nbsp; console.log(('theImg').height);&nbsp; &nbsp; &nbsp; &nbsp; $(".paysage") .css({'position' : 'absolute', 'top': y, 'left' : x})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .prepend($('<img>',{&nbsp; class:'theImg',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; src:'https://www.30millionsdamis.fr/uploads/pics/conseils-erreurs-chat-1171.jpg'}))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $(".theImg").prev().remove();&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;});body{&nbsp; width: 100vw;&nbsp; height: 100vh}.theImg{&nbsp; width :20em;&nbsp; height: auto;}.paysage {&nbsp; transform: translate(-50%, -50%);}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class = "paysage"> </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript