CSS and Jscript - Resize onClick image

Asked

Viewed 145 times

1

Good afternoon !!
I’m trying to execute the following code but I have no knowledge of how to resize the image to the size of the div, so it cuts the image and takes only the center :(
Can you help me??

function clickImagem(src)
{
  $('#conteudo').empty();
  var el = document.getElementById('conteudo');
  $(el).css('background',"url('"+src+"') no-repeat center ");
}
  #conteudo{
    height:200px;
    width:200px;
    float:left;
    background-color:#f1f;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div id="conteudo" class="conteudo"> </div>
<img src="https://tudocommoda.com/wp-content/uploads/2017/02/colar-de-namorados-cora%C3%A7%C3%A3o-1.jpg" onclick="clickImagem(this.src)">

  • See if this solves: $(el). css('background-image',"url('"+src+"')", 'background-size', '200px');

2 answers

2


Add the parameter cover in background-size

function clickImagem(src)
{
  $('#conteudo').empty();
  var el = document.getElementById('conteudo');
  $(el).css('background',"url('"+src+"') no-repeat center");
  $(el).css('background-size',"cover");
}
  #conteudo{
    height:200px;
    width:200px;
    float:left;
    background-color:#f1f;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div id="conteudo" class="conteudo"> </div>
<img src="https://tudocommoda.com/wp-content/uploads/2017/02/colar-de-namorados-cora%C3%A7%C3%A3o-1.jpg" onclick="clickImagem(this.src)">

  • 1

    It worked, thank you!

1

function clickImagem(src)
{
  $('#conteudo').empty();
  var el = document.getElementById('conteudo');
  $(el).html('<img src="'+src+'">')
}
 #conteudo{
    height:200px;
    width:200px;
    float:left;
    background-color:#f1f;
  }


img{
    width: 100%;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div id="conteudo" class="conteudo"> </div>
<img src="https://tudocommoda.com/wp-content/uploads/2017/02/colar-de-namorados-cora%C3%A7%C3%A3o-1.jpg" onclick="clickImagem(this.src)">
</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.