我使用javascript创建一个onclick按钮,根据颜色更改项目的图像。但是,单击按钮后,新图像将跟随原始图像的宽度和高度。有没有办法在点击按钮后放大图像?
这些是我的html,css和javascript代码。
function change1() {
eyeliner1.src = "https://s5.postimg.org/lj0ifekvr/Tattoo_Liner.png";
}
function change2() {
eyeliner1.src = "https://s5.postimg.org/6lllv5mif/Tattoo_Liner_Mad_Max_Brown.png";
}
.center {
display: block;
margin: 0 auto;
}
.button {
text-align: center;
padding: 15px 32px;
}
.buttondeco {
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 0 3px #888;
height: 30px;
width: 30px;
color: white;
text-decoration: none;
cursor: pointer;
margin-left: 5px;
}
<div id="eye">
<img class="center" src="https://s5.postimg.org/lj0ifekvr/Tattoo_Liner.png" id="eyeliner1" alt="Tattoo Liner" height="300" width="119">
<div class="button">
<button class="buttondeco" style="text-align:center; background-color: #000;" id="size" onclick="change1()"></button>
<button class="buttondeco" style="text-align:center; background-color: #644741;" onclick="change2()"></button>
</div>
</div>
答案 0 :(得分:0)
试试这个......相应地给出你想要的宽度和高度
function change1() {
eyeliner1.src = "https://s5.postimg.org/lj0ifekvr/Tattoo_Liner.png";
eyeliner1.height="500"; //Your desired Height
eyeliner1.width="219"; //Your desired Width
}
function change2() {
eyeliner1.src = "https://s5.postimg.org/6lllv5mif/Tattoo_Liner_Mad_Max_Brown.png";
eyeliner1.height="700"; //Your desired Height
eyeliner1.width="419"; //Your desired Width
}
.center {
display: block;
margin: 0 auto;
}
.button {
text-align: center;
padding: 15px 32px;
}
.buttondeco {
border: 2px solid #fff;
border-radius: 50%;
box-shadow: 0 0 0 3px #888;
height: 30px;
width: 30px;
color: white;
text-decoration: none;
cursor: pointer;
margin-left: 5px;
}
<div id="eye">
<img class="center" src="https://s5.postimg.org/lj0ifekvr/Tattoo_Liner.png" id="eyeliner1" alt="Tattoo Liner" height="300" width="119">
<div class="button">
<button class="buttondeco" style="text-align:center; background-color: #000;" id="size" onclick="change1()"></button>
<button class="buttondeco" style="text-align:center; background-color: #644741;" onclick="change2()"></button>
</div>
</div>
答案 1 :(得分:0)
您必须找到新图像的宽度或高度中的哪一个更接近原始图像。更改src后:
$('#eyeliner1').removeAttr('width');
$('#eyeliner1').removeAttr('height');
var newWidth = $('#eyeliner1').width();
var newHeight = $('#eyeliner1').height();
var widthIsCloserThanHeight = parseFloat(119/newWidth) > parseFloat(300/newHeight);
if(widthIsCloserThanHeight)
$('#eyeliner1').css('width', '119px').css('height', 'auto');
else
$('#eyeliner1').css('width', 'auto').css('height', '300px');
如您所说,图像非常大,此代码仅在新图像原始尺寸大于119px / 300px时有效。