我必须通过单击加号按钮将图像放大 20 像素,然后单击减号按钮将图像缩小 20 像素。图片宽度最大为 500px,最小宽度为 250px。
<div id="doc">
<div id="buttons">
<button id="plus" onclick="imagePlus()">+</button>
<button id="moins" onclick="imageMinus()">-</button>
</div>
<img id="sun" src="images/soleil.jpg" alt="soleil" />
</div>
我尝试使用clientWidth
来获取图像的当前宽度并增加它,但似乎不起作用
var imagePlus = function() {
var img = document.getElementById("sun");
var currWidth = img.clientWidth;
if(currWidth == 500){
null
} else{
img.style.width = (currWidth + 20) + "px";
}
}
var imageMinus = function() {
var img = document.getElementById("sun");
var currWidth = img.clientWidth;
if(currWidth == 250){
null
} else{
img.style.width = (currWidth - 20) + "px";
}
}
最佳答案
您需要通过这种方式为加号和减号按钮添加事件监听器,或者您也可以在加号和减号按钮上添加onclick事件。
const imagePlus = function () {
var img = document.getElementById("sun");
var currWidth = img.clientWidth;
if (currWidth == 500) {
null;
} else {
img.style.width = currWidth + 20 + "px";
}
};
const imageMinus = function () {
var img = document.getElementById("sun");
var currWidth = img.clientWidth;
if (currWidth == 250) {
null;
} else {
img.style.width = currWidth - 20 + "px";
}
};
document.querySelector("#plus").addEventListener("click", imagePlus);
document.querySelector("#minus").addEventListener("click", imageMinus);
关于javascript - 使用 Javascript 放大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71458956/